I have the code at the bottom of this message in a web server I'm running in a Digital Ocean Droplet. The app is a simple ear training program for instrumentalists. The URL is
https://etudes.ellisandgrant.com.
It works with no problems until the letsencrypt certificate expires every 90 days. ListenAndServeTLS() returns an error, the program exits and restarts (because I'm running under `entr - r`) and then falls into the default case which is plain http service. I'd like to prevent that since modern browsers (for very good reasons) show scary warnings about plain http sites.
I don't need absolute 100% uptime for the program. A few minutes unavailability while the cert is renewed would be perfectly acceptable. I just want to add a check at the restart to detect that the cert is expired and renew it automatically. How can I do that with packages from the Go standard library? ( I know Caddy is available but I'd prefer not to add a third-party dependency for what seems like a relatively simple task.)
<SNIP>
var serveSecure bool
var certpath, certkeypath string
if hostport == ":443" {
certpath, certkeypath, err = getCertPaths()
if err != nil {
log.Printf("Can't find SSL certificates: %v", err)
hostport = ":80"
}
serveSecure = true
}
log.Printf("serving on %s\n", hostport)
switch serveSecure {
case true:
if err := http.ListenAndServeTLS(hostport, certpath, certkeypath, nil); err != nil {
log.Fatalf("Could not listen on port %s : %v", hostport, err)
}
default:
if err := http.ListenAndServe(hostport, nil); err != nil {
log.Fatalf("Could not listen on port %s : %v", hostport, err)
}
}
/ getCertPaths attempts to retrieve a certficate and key for use with
// ListenAndServeTLS. It returns an error if either item cannot be found but
// does not otherwise attempt to validate them. That is left up to
// ListenAndServeTLS.
func getCertPaths() (certpath string, keypath string, err error) {
certpath = os.Getenv("IETUDE_CERT_PATH")
if certpath == "" {
err = fmt.Errorf("no environment variable IETUDE_CERT_PATH")
return
}
keypath = os.Getenv("IETUDE_CERTKEY_PATH")
if keypath == "" {
err = fmt.Errorf("no environment variable IETUDE_CERTKEY_PATH")
return
}
return
}