Skip to content

Instantly share code, notes, and snippets.

@KaiserWerk
Last active December 27, 2023 06:09
Show Gist options
  • Save KaiserWerk/3c1a5e16c4b85dac1923ecb4d1cbd1dc to your computer and use it in GitHub Desktop.
Save KaiserWerk/3c1a5e16c4b85dac1923ecb4d1cbd1dc to your computer and use it in GitHub Desktop.
Golang: Automatic TLS Certificate Reload
  • add certificate and privkey to the project folder
  • call via https, NOT http!
  • "GetCertificate() called!" is the output when the certificate get (re)loaded after not being cached anymore or when another browser is used
package main
import (
"crypto/tls"
"fmt"
"io"
"net/http"
)
func main() {
http.HandleFunc("/", handler)
s := &http.Server{
Addr: ":8080",
TLSConfig: &tls.Config{
GetCertificate: getCertificate,
},
}
if err := s.ListenAndServeTLS("", ""); err != nil {
fmt.Println(err)
}
}
func getCertificate(info *tls.ClientHelloInfo) (*tls.Certificate, error) {
fmt.Println("GetCertificate() called!")
fmt.Printf("ServerName: %s\n", info.ServerName)
caFiles, err := tls.LoadX509KeyPair("cert.pem", "key.pem")
if err != nil {
return nil, err
}
return &caFiles, nil
}
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Println("handler hit")
io.WriteString(w, "Hey")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment