Skip to content

Instantly share code, notes, and snippets.

@ellisda
Created September 26, 2018 22:18
Show Gist options
  • Save ellisda/8546f4cd9b83aa2b6381638eeb25c645 to your computer and use it in GitHub Desktop.
Save ellisda/8546f4cd9b83aa2b6381638eeb25c645 to your computer and use it in GitHub Desktop.
A simple golang http server with a shutdown route
package main
import (
"context"
"flag"
"fmt"
"log"
"net/http"
)
type server struct {
http http.Server
}
func main() {
port := flag.Int("port", 8080, "port to listen on")
flag.Parse()
mux := http.NewServeMux()
srv := server{
http: http.Server{
Addr: fmt.Sprintf(":%d", *port),
Handler: mux,
},
}
//example curl for this route: `curl -X POST http://localhost:8080 -d username=foo -H 'Content-Type: application/x-www-form-urlencoded'`
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
fmt.Fprintf(w, "error parsing form data")
} else {
fmt.Fprintf(w, "hello Form:%+v", r.Form)
for k, v := range r.Form {
fmt.Fprintf(w, " - %v : %v", k, v)
}
}
})
mux.HandleFunc("/shutdown", func(w http.ResponseWriter, r *http.Request) {
go srv.http.Shutdown(context.Background())
w.WriteHeader(202)
})
if err := srv.Run(); err != nil {
log.Fatalf("error running http server: %v\n", err)
}
}
func (s *server) Run() error {
log.Printf("Server Listening on %s", s.http.Addr)
return s.http.ListenAndServe()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment