From de5704b90eb5ba1c4a899926b50cdfb8e558987e Mon Sep 17 00:00:00 2001 From: "suguo.yao" Date: Thu, 20 Oct 2022 13:29:58 +0800 Subject: [PATCH] =?UTF-8?q?gin=E6=94=AF=E6=8C=81ssl?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- gin/gin.go | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/gin/gin.go b/gin/gin.go index 826af5e..32bfd4d 100644 --- a/gin/gin.go +++ b/gin/gin.go @@ -4,9 +4,11 @@ import ( "fmt" "log" "net/http" + "strconv" "time" "github.com/gin-gonic/gin" + "github.com/unrolled/secure" ) func Service(conf *Config) { @@ -15,11 +17,19 @@ func Service(conf *Config) { RootPath: "/", Addr: "0.0.0.0", Port: 80, + Ssl: false, + SslPem: "server.pem", + SslKey: "server.key", } } go func() { router := gin.New() routerSetup(router, &conf.RootPath) + + if conf.Ssl { + router.Use(tlsHandler(conf)) + } + s := &http.Server{ Addr: fmt.Sprintf("%s:%d", conf.Addr, conf.Port), Handler: router, @@ -28,6 +38,28 @@ func Service(conf *Config) { MaxHeaderBytes: 1 << 20, } log.Printf("start service on %s", fmt.Sprintf("%s:%d", conf.Addr, conf.Port)) - log.Fatal(s.ListenAndServe()) + + if conf.Ssl { + log.Fatal(s.ListenAndServeTLS(conf.SslPem, conf.SslKey)) + } else { + log.Fatal(s.ListenAndServe()) + } }() } + +func tlsHandler(conf *Config) gin.HandlerFunc { + return func(c *gin.Context) { + secureMiddleware := secure.New(secure.Options{ + SSLRedirect: true, + SSLHost: ":" + strconv.Itoa(conf.Port), + }) + err := secureMiddleware.Process(c.Writer, c.Request) + + // If there was an error, do not continue. + if err != nil { + return + } + + c.Next() + } +}