时间:2023-02-09 08:48:01 | 来源:建站知识
时间:2023-02-09 08:48:01 来源:建站知识
设置https访问:func main() { server := &http.Server{ Addr: ":8080", ... } go func() { if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed { log.Fatalf(err, "Listen: %s/n") } }() ...}
变为https监听:func main() { server := &http.Server{ Addr: ":8080", ... } go func() { if err := server.ListenAndServeTLS("conf/server.crt", "conf/server.key"); err != nil && err != http.ErrServerClosed { log.Fatalf(err, "Listen: %s/n") } }() ...}
其中ListenAndServeTLS方法的两个参数为SSL证书的下载文件,网上有专门生成证书的命令或工具,这种情况得到的证书,虽然可以访问https,但证书无效,浏览器地址栏提示不安全。go get github.com/unrolled/secure
利用secure包写一个中间件,设置http重定向到https具体哪个url上://设置http重定向到httpsfunc TlsHandler() gin.HandlerFunc { return func(c *gin.Context) { secureMiddleware := secure.New(secure.Options{ SSLRedirect: true, SSLHost: "dubinyang.xyz:8081", }) err := secureMiddleware.Process(c.Writer, c.Request) if err != nil { return } c.Next() }}
main函数里同时监听http和https:func main() { g:= gin.Default() //加载中间件 g.Use(TlsHandler()) server := &http.Server{ Addr: ":8080", ... } //监听http go func() { if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed { log.Fatalf(err, "Listen: %s/n") } }() //监听https go func() { //端口不可重复监听 //此处更换8080端口为8081,直接用gin的RunTLS()函数进行监听 //继续用server的ListenAndServeTLS()函数效果一样,建server2,Addr变为为":8081"即可 if err := g.RunTLS(":8081", "conf/server.crt", "conf/server.key"); err != nil && err != http.ErrServerClosed { log.Fatalf(err, "Listen: %s/n") } }() ...}
如果http监听80端口,https监听443端口,两个端口都可隐藏,重定向时地址栏不会显示端口变化。关键词:设置,访问