Go

Golang+Gin实现https

2019-12-06  本文已影响0人  天是透明的

首先你需要.crt  和 .key两个证书文件。我是通过opensssl自生成的证书,你也可以通过域名购买正规证书。

代码:  

 func InitRouter() {

    router := gin.Default()

    authorized := router.Group("test")

    registerAuthorized(authorized)

dirPath := filepath.Dir(os.Args[0])

    crtPath, err := filepath.Abs(dirPath + "/../server.crt") //.crt文件路径

    if err != nil {

        log.Fatal("server.crt未找到:", err)

    }

    keyPath, err := filepath.Abs(dirPath + "/../server.key") //.key文件路径

    if err != nil {

        log.Fatal("server.key未找到:", err)

    }

    //router.RunTLS(conf.JSONConf.Port, crtPath, keyPath)":8081"

    router.RunTLS(":8081", crtPath, keyPath)

}

func registerAuthorized(group *gin.RouterGroup) {

    group.GET(strings.ToLower("/gettest"), work.Example1())  //例子

    group.POST(strings.ToLower("/posttest"), work.Example2()) //例子

}

写了两个测试接口,https://localhost:8081/test/gettest 和 https://localhost:8081/test/posttest。因为是自生成的证书,客户端访问的时候记得关闭证书验证

上一篇 下一篇

猜你喜欢

热点阅读