go/webutil/listenandserve.go

25 lines
606 B
Go
Raw Normal View History

2024-11-11 05:36:55 +00:00
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()
}