关于golang:golang-gin框架实现https访问

10次阅读

共计 1138 个字符,预计需要花费 3 分钟才能阅读完成。

起因:

 在应用 facebook 三方登陆时,无效 OAuth 跳转 URI 这一项目前看来只反对 https 拜访,本地测试就要实现 https

mkcert 简介
mkcert 是一个应用 go 语言编写的生成本地自签证书的小工具,具备跨平台,应用简略,反对多域名,主动信赖 CA 等一系列不便的个性,可供本地开发时疾速创立 https 环境应用。
github 介绍:https://github.com/FiloSottil…

macOS
On macOS, use Homebrew

brew install mkcert
brew install nss # if you use Firefox
$ mkcert -install
Created a new local CA 💥
The local CA is now installed in the system trust store! ⚡️
The local CA is now installed in the Firefox trust store (requires browser restart)! 🦊

$ mkcert example.com "*.example.com" example.test localhost 127.0.0.1 ::1

Created a new certificate valid for the following names 📜
 - "example.com"
 - "*.example.com"
 - "example.test"
 - "localhost"
 - "127.0.0.1"
 - "::1"

The certificate is at "./example.com+5.pem" and the key at "./example.com+5-key.pem" ✅

代码开发:加一个中间件

package main

import (
    "github.com/gin-gonic/gin"
    "github.com/unrolled/secure"
)

func main() {router := gin.Default()
    router.Use(LoadTls())
    // 开启端口监听
    router.RunTLS(":8080", "localhost.pem", "localhost-key.pem")
}

func LoadTls() gin.HandlerFunc {return func(c *gin.Context) {
        middleware := secure.New(secure.Options{
            SSLRedirect: true,
            SSLHost:     "localhost:8000",
        })
        err := middleware.Process(c.Writer, c.Request)
        if err != nil {
            // 如果呈现谬误,请不要持续。fmt.Println(err)
            return
        }
        // 持续往下解决
        c.Next()}
}
正文完
 0