Skip to content

Instantly share code, notes, and snippets.

@xlab
Created July 27, 2015 10:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xlab/2ea988fca7c8e0129f4a to your computer and use it in GitHub Desktop.
Save xlab/2ea988fca7c8e0129f4a to your computer and use it in GitHub Desktop.
golang closer with manners webserver
package main
import (
"io"
"log"
"net/http"
"time"
"github.com/braintree/manners"
"github.com/xlab/closer"
)
func main() {
// start the http server
http.HandleFunc("/", hello)
server := manners.NewWithServer(&http.Server{Addr: ":8080", Handler: nil})
// a channel to check on exit that ListenAndServe is done
exitChan := make(chan struct{})
closer.Bind(func() {
<-exitChan
})
// bind server.Close to be called if app is exiting because of a signal
closer.Bind(func() {
server.Close()
})
if err := server.ListenAndServe(); err != nil {
log.Fatalln(err)
}
close(exitChan)
}
func hello(w http.ResponseWriter, r *http.Request) {
// pretend to do some work
time.Sleep(3000 * time.Millisecond)
io.WriteString(w, "Hello world!")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment