Skip to content

Instantly share code, notes, and snippets.

@alinz
Created July 11, 2019 19:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alinz/6fdeae96255cdcabd468fe9d8d4c75ab to your computer and use it in GitHub Desktop.
Save alinz/6fdeae96255cdcabd468fe9d8d4c75ab to your computer and use it in GitHub Desktop.
Share tls config with server and client in golang
package main
import (
"bytes"
"crypto/tls"
"crypto/x509"
"io"
"io/ioutil"
"log"
"net/http"
"time"
)
func main() {
// certificate
caCert, err := ioutil.ReadFile("./cert/ca.crt")
if err != nil {
panic(err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
cert, err := tls.LoadX509KeyPair("./cert/service.crt", "./cert/service.key")
if err != nil {
panic(err)
}
tlsConfig := &tls.Config{
RootCAs: caCertPool,
Certificates: []tls.Certificate{cert},
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: caCertPool,
ServerName: "server",
}
go func() {
server := &http.Server{
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello world"))
}),
}
server.TLSConfig = tlsConfig
ln, err := tls.Listen("tcp", ":10000", tlsConfig)
if err != nil {
panic(err)
}
err = server.Serve(ln)
if err != nil {
panic(err)
}
}()
time.Sleep(1 * time.Second)
client := &http.Client{}
client.Transport = &http.Transport{
TLSClientConfig: tlsConfig,
}
resp, err := client.Get("https://localhost:10000")
if err != nil {
log.Fatal(err)
}
var buffer bytes.Buffer
io.Copy(&buffer, resp.Body)
println(buffer.String())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment