为localhost一步生成自签名证书
openssl req -x509 -days 365 -out localhost.crt -keyout localhost.key \
-newkey rsa:2048 -nodes -sha256 \
-subj '/CN=localhost' -extensions EXT -config <( \
printf "[dn]\nCN=localhost\n[req]\ndistinguished_name = dn\n[EXT]\nsubjectAltName=DNS:localhost\nkeyUsage=digitalSignature\nextendedKeyUsage=serverAuth")
golang 可以使用这个库 https://github.com/unrolled/secure
gin示例
package main
import (
"github.com/gin-gonic/gin"
"github.com/unrolled/secure"
)
func main() {
router := gin.Default()
router.Use(TlsHandler())
router.RunTLS(":443", "localhost.crt", "localhost.key")
}
func TlsHandler() gin.HandlerFunc {
return func(c *gin.Context) {
secureMiddleware := secure.New(secure.Options{
SSLRedirect: true,
SSLHost: "localhost:8080",
})
err := secureMiddleware.Process(c.Writer, c.Request)
// If there was an error, do not continue.
if err != nil {
return
}
c.Next()
}
}