cmd/gerritbot, internal/https: handle error from https.ListenAndServe
Document that https.ListenAndServe always returns a non-nil error,
and use that property to stop gerritbot if the HTTPS server fails
to run.
Remove an unneccessary check for ln != nil in https.ListenAndServe.
net.Listen returns a valid listener when err == nil, and the
err != nil case is already handled above.
Change-Id: Ibbadd551aa36b5376bf062011f12e3e3787bd6b3
Reviewed-on: https://go-review.googlesource.com/c/159698
Reviewed-by: Andrew Bonventre <andybons@golang.org>
diff --git a/cmd/gerritbot/gerritbot.go b/cmd/gerritbot/gerritbot.go
index 82dd1d7..23078eb 100644
--- a/cmd/gerritbot/gerritbot.go
+++ b/cmd/gerritbot/gerritbot.go
@@ -64,10 +64,11 @@
b.initCorpus(ctx)
go b.corpusUpdateLoop(ctx)
- https.ListenAndServe(http.HandlerFunc(handleIndex), &https.Options{
+ err = https.ListenAndServe(http.HandlerFunc(handleIndex), &https.Options{
Addr: *listen,
AutocertCacheBucket: *autocertBucket,
})
+ log.Fatalln(err)
}
func defaultWorkdir() string {
diff --git a/internal/https/https.go b/internal/https/https.go
index c63280d..54821c9 100644
--- a/internal/https/https.go
+++ b/internal/https/https.go
@@ -37,6 +37,8 @@
// ListenAndServe serves the given handler by HTTPS (and HTTP, redirecting to
// HTTPS) using the provided options.
+//
+// ListenAndServe always returns a non-nil error.
func ListenAndServe(handler http.Handler, opt *Options) error {
if opt == nil {
opt = defaultOptions
@@ -47,18 +49,16 @@
}
errc := make(chan error)
- if ln != nil {
- go func() {
- var h http.Handler
- if opt.AutocertCacheBucket != "" {
- // handler is served primarily via HTTPS, so just redirect HTTP to HTTPS.
- h = http.HandlerFunc(redirectToHTTPS)
- } else {
- h = handler
- }
- errc <- fmt.Errorf("http.Serve = %v", http.Serve(ln, h))
- }()
- }
+ go func() {
+ var h http.Handler
+ if opt.AutocertCacheBucket != "" {
+ // handler is served primarily via HTTPS, so just redirect HTTP to HTTPS.
+ h = http.HandlerFunc(redirectToHTTPS)
+ } else {
+ h = handler
+ }
+ errc <- fmt.Errorf("http.Serve = %v", http.Serve(ln, h))
+ }()
if opt.AutocertCacheBucket != "" {
go func() { errc <- serveAutocertTLS(handler, opt.AutocertCacheBucket) }()
}
@@ -78,6 +78,8 @@
// serveAutocertTLS serves the handler h on port 443 using the given GCS bucket
// for its autocert cache. It will only serve on domains of the form *.golang.org.
+//
+// serveAutocertTLS always returns a non-nil error.
func serveAutocertTLS(h http.Handler, bucket string) error {
ln, err := net.Listen("tcp", ":443")
if err != nil {