使用自己证书

用 GIN 框架添加一个 unrolled/secure 中间件,导入自己的证书。

  1. package main
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "github.com/unrolled/secure"
  5. )
  6. func main() {
  7. router := gin.Default()
  8. router.Use(TlsHandler())
  9. router.RunTLS(":8080", "ssl.pem", "ssl.key")
  10. }
  11. func TlsHandler() gin.HandlerFunc {
  12. return func(c *gin.Context) {
  13. secureMiddleware := secure.New(secure.Options{
  14. SSLRedirect: true,
  15. SSLHost: "localhost:8080",
  16. })
  17. err := secureMiddleware.Process(c.Writer, c.Request)
  18. // If there was an error, do not continue.
  19. if err != nil {
  20. return
  21. }
  22. c.Next()
  23. }
  24. }

自动生成证书

用 GIN 框架添加一个 gin-gonic/autotls 中间件,自动生成CA证书并使用。

  1. package main
  2. import (
  3. "log"
  4. "net/http"
  5. "github.com/gin-gonic/autotls"
  6. "github.com/gin-gonic/gin"
  7. )
  8. func main() {
  9. r := gin.Default()
  10. // Ping handler
  11. r.GET("/ping", func(c *gin.Context) {
  12. c.String(http.StatusOK, "pong")
  13. })
  14. log.Fatal(autotls.Run(r, "example1.com", "example2.com"))
  15. }