Skip to content

Instantly share code, notes, and snippets.

@pavolloffay
Created August 13, 2020 14:49
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 pavolloffay/ae86424b44acb51198788f352d5568c8 to your computer and use it in GitHub Desktop.
Save pavolloffay/ae86424b44acb51198788f352d5568c8 to your computer and use it in GitHub Desktop.
reload certs
package tlscfg
import (
"crypto/tls"
"fmt"
"github.com/stretchr/testify/require"
"go.uber.org/zap"
"io/ioutil"
"net/http"
"testing"
"time"
)
func TeastSaerver(t *testing.T) {
tlsOpts := Options{
CertPath: "/tmp/certs/server.crt",
KeyPath: "/tmp/certs/server.key",
ClientCAPath: "/tmp/certs/ca.crt",
}
tlsCfg, err := tlsOpts.Config()
require.NoError(t, tlsOpts.ReloadCertificates(tlsCfg, zap.NewExample()))
require.NoError(t, err)
require.NotNil(t, tlsCfg)
tlsCfg.ClientAuth = tls.RequireAndVerifyClientCert
http.HandleFunc("/", handler)
s := &http.Server{
Addr: ":8080",
TLSConfig: tlsCfg,
}
if err := s.ListenAndServeTLS("", ""); err != nil {
fmt.Println(err.Error())
}
}
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello")
}
func TesatClient(t *testing.T) {
opts := Options{
CertPath: "/tmp/certs/client.crt",
KeyPath: "/tmp/certs/client.key",
CAPath: "/tmp/certs/ca.crt",
Enabled: true,
}
tlsCfg, err := opts.Config()
require.NoError(t, err)
require.NotNil(t, tlsCfg)
require.NoError(t, opts.ReloadCertificates(tlsCfg, zap.NewExample()))
client := &http.Client{
Transport: &http.Transport{
TLSClientConfig: tlsCfg,
},
}
for {
time.Sleep(time.Second * 3)
response, err := client.Get("https://localhost:8080")
if err != nil {
fmt.Println("got error response")
continue
}
body, err := ioutil.ReadAll(response.Body)
require.NoError(t, err)
fmt.Println(string(body))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment