go/webutil/listenandserve.go
2024-11-11 06:36:55 +01:00

25 lines
606 B
Go

package webutil
import (
"errors"
"net/http"
"strings"
"golang.org/x/crypto/acme/autocert"
)
// Serve requests using the given http.Server. If srv.Addr has the format
// `hostname:https`, then use autocert to manage certificates for the domain.
//
// For http on port 80, you can use :http.
func ListenAndServe(srv *http.Server) error {
if strings.HasSuffix(srv.Addr, ":https") {
hostname := strings.TrimSuffix(srv.Addr, ":https")
if len(hostname) == 0 {
return errors.New("https requires a hostname")
}
return srv.Serve(autocert.NewListener(hostname))
}
return srv.ListenAndServe()
}