今天在使用golang请求微信服务时,出现错误。
x509: certificate signed by unknown authority
从日志来看go实现的Client端默认也是要对服务端传过来的数字证书进行校验的,但客户端提示:这个证书是由不知名CA签发 的!
对应这个问题,有2种不同的解决办法。
client端忽略证书的校验
示例
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 
 | package main
 import (
 "fmt"
 "io/ioutil"
 "net/http"
 )
 
 func main() {
 resp, err := http.Get("https://localhost:8081")
 if err != nil {
 fmt.Println("error:", err)
 return
 }
 defer resp.Body.Close()
 body, err := ioutil.ReadAll(resp.Body)
 fmt.Println(string(body))
 }
 
 | 
此时运行客户端,会提示错误
| 1
 | error: Get https://localhost:8081: x509: certificate signed by unknown authority
 | 
可以修改代码,忽略对证书的校验:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 
 | package main
 import (
 "crypto/tls"
 "fmt"
 "io/ioutil"
 "net/http"
 )
 
 func main() {
 tr := &http.Transport{
 TLSClientConfig:    &tls.Config{InsecureSkipVerify: true},
 }
 client := &http.Client{Transport: tr}
 resp, err := client.Get("https://localhost:8081")
 
 if err != nil {
 fmt.Println("error:", err)
 return
 }
 defer resp.Body.Close()
 body, err := ioutil.ReadAll(resp.Body)
 fmt.Println(string(body))
 }
 
 | 
设置tls.Config的InsecureSkipVerify为true,client将不再对服务端的证书进行校验
添加CA证书
可以添加ca-certificates证书
可以将CA证书打包到docker镜像
| 12
 
 | RUN apk --no-cache add ca-certificates \&& update-ca-certificates
 
 | 
使用apk命令安装我们需要的包ca-certificates(以便使用TLS的页面)
参考文章
Alpine Linux添加Let’s Encrypt CA证书或者自签CA证书
golang GET 出现 x509: certificate signed by unknown authority