美文网首页
本地Go服务启用 HTTPS 支持

本地Go服务启用 HTTPS 支持

作者: 沙漠中的猴 | 来源:发表于2020-06-29 16:20 被阅读0次

生成证书

  1. 生成私钥文件(server.key) 和 自签发的数字证书(server.crt)
openssl req -new -nodes -x509 -out conf/server.crt -keyout conf/server.key -days 3650 -subj "/C=DE/ST=NRW/L=Earth/O=Random Company/OU=IT/CN=127.0.0.1/emailAddress=18345070876@163.com"
  1. 在配置文件中配置私钥文件、数字证书文件的路径和 HTTPS 端口,供 ListenAndServeTLS() 函数调用。
  1. main 函数中添加 ListenAndServeTLS() 调用。启动 HTTPS 端口
// 启动服务
    cert := viper.GetString("tls.cert")
    key := viper.GetString("tls.key")
    if cert != "" && key != "" {
        go func() {
            log.Println("Start to listening requests on https address: ", viper.GetString("tls.addr"))
            log.Println(http.ListenAndServeTLS(viper.GetString("tls.addr"), cert, key, g).Error())
        }()
    }

Curl 访问服务

不携带证书

curl -X GET  -H "Content-Type: application/json" https://127.0.0.1:9990/v1/user

报错:

curl: (60) SSL certificate problem: self signed certificate
More details here: https://curl.haxx.se/docs/sslcerts.html

curl performs SSL certificate verification by default, using a "bundle"
 of Certificate Authority (CA) public keys (CA certs). If the default
 bundle file isn't adequate, you can specify an alternate file
 using the --cacert option.
If this HTTPS server uses a certificate signed by a CA represented in
 the bundle, the certificate verification probably failed due to a
 problem with the certificate (it might be expired, or the name might
 not match the domain name in the URL).
If you'd like to turn off curl's verification of the certificate, use
 the -k (or --insecure) option.
HTTPS-proxy has similar options --proxy-cacert and --proxy-insecure.

携带证书

curl -X GET  -H "Content-Type: application/json" https://127.0.0.1:9990/v1/user   --cacert conf/server.crt --cert conf/server.crt --key conf/server.key

正常返回信息。

相关文章

网友评论

      本文标题:本地Go服务启用 HTTPS 支持

      本文链接:https://www.haomeiwen.com/subject/whaofktx.html