examples/server: Generate new certificates when they expire

This commit is contained in:
adnano
2020-10-13 14:22:15 -04:00
parent a0aa135534
commit db89a34935
5 changed files with 43 additions and 7 deletions

View File

@@ -12,7 +12,7 @@ import (
func main() {
host := "localhost"
duration := 365 * 24 * time.Hour
duration := 2 * time.Minute
crt, key, err := gmi.NewRawCertificate(host, duration)
if err != nil {
log.Fatal(err)

View File

@@ -3,7 +3,9 @@
package main
import (
"crypto/tls"
"log"
"time"
"git.sr.ht/~adnano/gmi"
)
@@ -13,6 +15,33 @@ func main() {
if err := server.CertificateStore.Load("/var/lib/gemini/certs"); err != nil {
log.Fatal(err)
}
server.GetCertificate = func(hostname string, store *gmi.CertificateStore) *tls.Certificate {
cert, err := store.Lookup(hostname)
if err != nil {
switch err {
case gmi.ErrInvalidCertificate:
log.Print("Old certificate expired, creating new one")
// Generate a new certificate if the old one is expired.
crt, key, err := gmi.NewRawCertificate(hostname, time.Minute)
if err != nil {
// Failed to generate new certificate, abort
return nil
}
// Store and return the new certificate
err = gmi.WriteX509KeyPair("/var/lib/gemini/certs/"+hostname, crt, key)
if err != nil {
return nil
}
newCert, err := tls.X509KeyPair(crt, key)
if err != nil {
return nil
}
store.Add(hostname, newCert)
return &newCert
}
}
return cert
}
var mux gmi.ServeMux
mux.Handle("/", gmi.FileServer(gmi.Dir("/var/www")))