如何在GO中创建带有ca证书的tls客户端?

时间:2016-07-26 06:54:02

标签: ssl go https net-http

我想使用GO中的net/http创建一个tls客户端,如何根据ca证书创建它?

1 个答案:

答案 0 :(得分:4)

package main

import (
    "crypto/tls"
    "crypto/x509"
    "flag"
    "io/ioutil"
    "log"
    "net/http"
)

var (
    certFile = flag.String("cert", "someCertFile", "A PEM eoncoded certificate file.")
    keyFile  = flag.String("key", "someKeyFile", "A PEM encoded private key file.")
    caFile   = flag.String("CA", "someCertCAFile", "A PEM eoncoded CA's certificate file.")
)

func main() {
    flag.Parse()

    // Load client cert
    cert, err := tls.LoadX509KeyPair(*certFile, *keyFile)
    if err != nil {
        log.Fatal(err)
    }

    // Load CA cert
    caCert, err := ioutil.ReadFile(*caFile)
    if err != nil {
        log.Fatal(err)
    }
    caCertPool := x509.NewCertPool()
    caCertPool.AppendCertsFromPEM(caCert)

    // Setup HTTPS client
    tlsConfig := &tls.Config{
        Certificates: []tls.Certificate{cert},
        RootCAs:      caCertPool,
    }
    tlsConfig.BuildNameToCertificate()
    transport := &http.Transport{TLSClientConfig: tlsConfig}
    client := &http.Client{Transport: transport}

    // Do GET something
    resp, err := client.Get("https://localdev.local:8443")
    if err != nil {
        log.Fatal(err)
    }
    defer resp.Body.Close()

    // Dump response
    data, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        log.Fatal(err)
    }
    log.Println(string(data))
}

主要是借用gist。这是一篇很棒的文章,可以在Go中使用TLS:https://ericchiang.github.io/tls/go/https/2015/06/21/go-tls.html