Skip to content

Instantly share code, notes, and snippets.

@chriswhitcombe
Created June 25, 2015 20:35
Show Gist options
  • Save chriswhitcombe/00d94c106f06d230cb2d to your computer and use it in GitHub Desktop.
Save chriswhitcombe/00d94c106f06d230cb2d to your computer and use it in GitHub Desktop.
Secure client in go (TLS Mutual Auth)
package main
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"log"
"net/http"
)
func main() {
// Load client cert
cert, err := tls.LoadX509KeyPair("selfsigned.crt", "selfsigned.key")
if err != nil {
log.Fatal(err)
}
// Load CA cert
caCert, err := ioutil.ReadFile("../secure-server/selfsigned.crt")
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}
resp, err := client.Get("https://localhost:8080/hello")
if err != nil {
fmt.Println(err)
}
contents, err := ioutil.ReadAll(resp.Body)
fmt.Printf("%s\n", string(contents))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment