Created
October 19, 2018 23:46
-
-
Save AmaranthLIS/455062b46186d960f29c117f7791be53 to your computer and use it in GitHub Desktop.
Golang: Shutdown HTTP server by requesting specific URL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"fmt" | |
"log" | |
"net/http" | |
) | |
func main() { | |
m := http.NewServeMux() | |
s := http.Server{Addr: ":8000", Handler: m} | |
ctx, cancel := context.WithCancel(context.Background()) | |
defer cancel() | |
m.Handle("/", &myHandler{cancel}) | |
go func() { | |
log.Printf("Starting server on port 8000") | |
if err := s.ListenAndServe(); err != nil { | |
if err != http.ErrServerClosed { | |
log.Fatal(err) | |
} | |
} | |
}() | |
select { | |
case <-ctx.Done(): | |
log.Printf("Shutting down server") | |
s.Shutdown(ctx) | |
} | |
} | |
type myHandler struct { | |
cancel context.CancelFunc | |
} | |
func (s *myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
switch r.URL.Path { | |
case "/shutdown": | |
log.Printf("Shutdown requested") | |
fmt.Fprint(w, "OK") | |
s.cancel() | |
default: | |
fmt.Fprint(w, "OK") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment