Skip to content

Instantly share code, notes, and snippets.

@d4z3x
Forked from KaiserWerk/auto-cert-reload.go
Created November 21, 2023 06:49
Show Gist options
  • Save d4z3x/b9f617a06f8118b0db688018998b257d to your computer and use it in GitHub Desktop.
Save d4z3x/b9f617a06f8118b0db688018998b257d 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