Skip to content

Instantly share code, notes, and snippets.

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

What would you like to do?
Shutdown HTTP server by requesting specific URL in Golang
package main
import (
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 {
select {
case <-ctx.Done():
log.Printf("Shutting down server")
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")
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.