zoukankan      html  css  js  c++  java
  • golang GET 出现 x509: certificate signed by unknown authority

    我们编写一个Go程序来尝试与这个HTTPS server建立连接并通信。

    //gohttps/4-https/client1.go
    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))
    }

    运行这个client,我们得到如下错误:

    $go run client1.go
    error: Get https://localhost:8081: x509: certificate signed by unknown authority

    此时服务端也给出了错误日志提示:
    2015/04/30 16:03:31 http: TLS handshake error from 127.0.0.1:62004: remote error: bad certificate

    显然从客户端日志来看,go实现的Client端默认也是要对服务端传过来的数字证书进行校验的,但客户端提示:这个证书是由不知名CA签发 的!

    我们可以修改一下client1.go的代码,让client端略过对证书的校验:

    //gohttps/4-https/client2.go
    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将不再对服务端的证书进行校验。执行后的结果 也证实了这一点:
    $go run client2.go
    Hi, This is an example of http service in golang!

  • 相关阅读:
    oracle创建表空间自增长和创建用户
    Cmd Markdown 简明语法手册
    Excel VBA修改不同文件簿sheet页名字
    常用JS(JQ)插件研究
    CSS颜色大全(转载)
    React框架学习
    不同浏览器中空格符的兼容问题
    VHDL----基础知识1
    串口通讯1---单片机
    Qt5 程序发布打包
  • 原文地址:https://www.cnblogs.com/rxbook/p/7595570.html
Copyright © 2011-2022 走看看