example:

1.使用安全套接字中间件,secure即可实现,HTTPS支持。

2.利用工具可以生成私钥key.pem和证书cert.pem

Golang标准库crypto/tls里有generate_cert.go,可以生成私钥key.pem和证书cert.pem,host参数是必须的,需要注意的是默认有效期是1年。

windows平台运行如下命令:

go.exe run  C:\Go\src\crypto\tls\generate_cert.go --host="localhost"

linux平台运行如下命令:

go run $GOROOT/src/crypto/tls/generate_cert.go --host="localhost"

 3.将生成的key.pem、cert.pem和以下代码放在同一目录下

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()
    }
}