使用自己证书
用 GIN 框架添加一个 unrolled/secure 中间件,导入自己的证书。
package main
import (
"github.com/gin-gonic/gin"
"github.com/unrolled/secure"
)
func main() {
router := gin.Default()
router.Use(TlsHandler())
router.RunTLS(":8080", "ssl.pem", "ssl.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()
}
}
自动生成证书
用 GIN 框架添加一个 gin-gonic/autotls 中间件,自动生成CA证书并使用。
package main
import (
"log"
"net/http"
"github.com/gin-gonic/autotls"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
// Ping handler
r.GET("/ping", func(c *gin.Context) {
c.String(http.StatusOK, "pong")
})
log.Fatal(autotls.Run(r, "example1.com", "example2.com"))
}