Skip to content

Instantly share code, notes, and snippets.

@int128 int128/main.go
Created Mar 23, 2018

Embed
What would you like to do?
Shutdown HTTP server by requesting specific URL in Golang
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
You can’t perform that action at this time.