Skip to content

Instantly share code, notes, and snippets.

@AmaranthLIS
Created October 19, 2018 23:46
Show Gist options
  • Save AmaranthLIS/455062b46186d960f29c117f7791be53 to your computer and use it in GitHub Desktop.
Save AmaranthLIS/455062b46186d960f29c117f7791be53 to your computer and use it in GitHub Desktop.
Golang: Shutdown HTTP server by requesting specific URL
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