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 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题