Created
March 23, 2018 01:06
-
-
Save int128/f15755fa35475584b90ffc219f222afb to your computer and use it in GitHub Desktop.
Shutdown HTTP server by requesting specific URL in Golang
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