Created
December 12, 2020 07:36
-
-
Save piotrpersona/a91fba6579111ffa348abd885541065d to your computer and use it in GitHub Desktop.
Golang multiserver
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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