Skip to content

Instantly share code, notes, and snippets.

@piotrpersona
Created December 12, 2020 07:36
Show Gist options
  • Save piotrpersona/a91fba6579111ffa348abd885541065d to your computer and use it in GitHub Desktop.
Save piotrpersona/a91fba6579111ffa348abd885541065d to your computer and use it in GitHub Desktop.
Golang multiserver
package main
import (
"context"
"fmt"
"net/http"
)
func shutdown(ready chan bool) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
ready <- false
w.WriteHead(http.StatusOK)
w.Write("Shutting down")
}
}
func health(ready chan bool) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write(fmt.Sprintf("Ready: %v", <-ready))
}
}
func main() {
mainServer := http.Server{Addr: ":8080", Handler: http.Handler(shutdown(ready))}
healthServer := http.Server{Addr: ":9000", Handler: health(ready)}
ready := make(chan bool)
go func() {
healthServer.ListenAndServe()
}()
go func() {
ready <- true
mainServer.ListenAndServe()
}()
select {
case r := <-ready:
if !r {
mainServer.Shutdown(context.Background())
healthServer.Shutdown(context.Background())
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment