Golang/Gin框架添加对HTTPS的支持

栏目: Go · 发布时间: 5年前

内容简介:HTTPS配置步骤:用 GIN 框架添加一个 github.com/unrolled/secure 中间件就可以了.下面是一个简单的示例代码:

HTTPS配置步骤:

  1. 首先在阿里云搞定ICP域名备案
  2. 添加一个子域名
  3. 给子域名申请免费 SSL 证书, 然后下载证书对应的 pem 和 key 文件.

用 GIN 框架添加一个 github.com/unrolled/secure 中间件就可以了.

下面是一个简单的示例代码:

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

上面代码直接在子域名前添加 HTTPS 就可以安全通讯了.


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

New Dark Age

New Dark Age

James Bridle / Verso Books / 2018-7-17 / GBP 16.99

As the world around us increases in technological complexity, our understanding of it diminishes. Underlying this trend is a single idea: the belief that our existence is understandable through comput......一起来看看 《New Dark Age》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具