I am building a command line app which needs to start its own HTTP server. My idea is to start the http server inside a goroutine in my main program like this:
func main() {
go myserver()
// perform lots of time-consuming tasks
}
func myserver() {
s := &http.Server{
Addr: ":8080",
Handler: MyHandler{},
}
log.Fatal(s.ListenAndServe())
}
- My main function needs to be able to tell the goroutine to die. Since the webserver is blocking on the
ListenAndServe
method, there is no way of signalling via async.WaitGroup
or a channel. - One idea I have is to make a HTTP POST to the webserver and ask it to commit suicide on receiving a specific agreed-upon value.
Are there other alternatives that are idiomatic to golang ?