dongta1824 2018-09-12 15:18
浏览 215
已采纳

传输选项以确保Net / http客户端通过TLS 1.2连接

I have a go service that makes REST requests to an HTTP server that I don't control. A customer asked my to "confirm" that my service is connecting via TLS 1.2. Is that something that I can do in code?

Current code looks something like this:

request, _ := http.NewRequest("PUT",
    "https://example.com/path/to/endpoint",
    bytes.NewReader(json))

client := &http.Client{}

response, _ := client.Do(request)
defer response.Body.Close()

str, err := ioutil.ReadAll(response.Body)

Based on a quick read of the docs I believe I need to use a Transport and build my client using that transport. Something like this:

tr := &http.Transport{
    ... some options here ...
}
client := &http.Client{Transport: tr}

But I'm not sure what options I should set.

  • 写回答

2条回答 默认 最新

  • douxian1895 2018-09-12 15:42
    关注

    At the time of writing, Go will speak TLS 1.2 automatically if the server supports it.

    tls.ConnectionState reports various negotiated TLS parameters of a connection, including the protocol version.

    To get the underlying TLS connection for an HTTP client it is easiest to set the DialTLS field of the Transport to a function that establishes and remembers the connection. Once the response arrived (but before you close the response body!), call tls.Conn.ConnectionState:

    package main
    
    import (
        "crypto/tls"
        "fmt"
        "log"
        "net"
        "net/http"
    )
    
    func main() {
        var (
            conn *tls.Conn
            err  error
        )
    
        tlsConfig := http.DefaultTransport.(*http.Transport).TLSClientConfig
    
        c := &http.Client{
            Transport: &http.Transport{
                DialTLS: func(network, addr string) (net.Conn, error) {
                    conn, err = tls.Dial(network, addr, tlsConfig)
                    return conn, err
                },
            },
        }
    
        res, err := c.Get("https://example.com")
        if err != nil {
            log.Fatal(err)
        }
    
        versions := map[uint16]string{
            tls.VersionSSL30: "SSL",
            tls.VersionTLS10: "TLS 1.0",
            tls.VersionTLS11: "TLS 1.1",
            tls.VersionTLS12: "TLS 1.2",
        }
    
        fmt.Println(res.Request.URL)
        fmt.Println(res.Status)
        v := conn.ConnectionState().Version
        fmt.Println(versions[v])
    
        res.Body.Close()
    }
    
    // Output:
    // https://example.com
    // 200 OK
    // TLS 1.2
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办