How to send cacert , cert and key with https request in GoLang?

Issue

I am new to GoLang. Can anyone please help me with the code in GoLang for the following curl request.

curl -v --cacert ca.crt --cert tls.crt --key tls.key --location --request POST 'https://<.......>' --header 'Content-Type: application/x-www-form-urlencoded'

Solution

From https://smallstep.com/hello-mtls/doc/combined/go/go step 5.

This should do wat you want it to, you just have to specify another URL, and change the file names in the example.

// ...

caCert, _ := ioutil.ReadFile("ca.crt")
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)

cert, _ := tls.LoadX509KeyPair("client.crt", "client.key")

client := &http.Client{
    Transport: &http.Transport{
        TLSClientConfig: &tls.Config{
            RootCAs: caCertPool,
            Certificates: []tls.Certificate{cert},
        },
    },
}

// Make a request
r, err := client.Get("https://myserver.internal.net:9443")

// ...

Answered By – Dylan Reimerink

Answer Checked By – Terry (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.