生成证书
- 生成私钥文件(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"
- 在配置文件中配置私钥文件、数字证书文件的路径和 HTTPS 端口,供
ListenAndServeTLS()
函数调用。
- 在
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
正常返回信息。
网友评论