Skip to content

Instantly share code, notes, and snippets.

@pmtabe1
Forked from michaljemala/tls-client.go
Created December 13, 2022 12:55
Show Gist options
  • Save pmtabe1/d51b86b41705bc1003324f34562cfcb7 to your computer and use it in GitHub Desktop.
Save pmtabe1/d51b86b41705bc1003324f34562cfcb7 to your computer and use it in GitHub Desktop.
SSL Client Authentication Golang sample
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://goldportugal.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))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment