Last active
July 29, 2018 14:18
-
-
Save beigna/d80fa71ae49527e1ddcaf359b4ff488b to your computer and use it in GitHub Desktop.
Don't kill the request! - https://stackoverflow.com/questions/51579812/my-graceful-stop-http-listenandserve-fails
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 ( | |
// "encoding/json" | |
"context" | |
"fmt" | |
"net/http" | |
"os" | |
"os/signal" | |
"syscall" | |
"time" | |
"github.com/gorilla/mux" | |
log "github.com/sirupsen/logrus" | |
) | |
func getEnv(key, fallback string) string { | |
value, exists := os.LookupEnv(key) | |
if exists { | |
return value | |
} | |
return fallback | |
} | |
func newRouter() *mux.Router { | |
r := mux.NewRouter() | |
r.HandleFunc("/about", handler).Methods("GET") | |
return r | |
} | |
func init() { | |
log.SetOutput(os.Stdout) | |
} | |
func main() { | |
log.Infof("Starting (PID %d)...", os.Getpid()) | |
stop := make(chan os.Signal, 1) | |
signal.Notify(stop, syscall.SIGTERM) | |
signal.Notify(stop, syscall.SIGINT) | |
listenAt := fmt.Sprintf("%s:%s", getEnv("HOST", "127.0.0.1"), getEnv("PORT", "8000")) | |
r := newRouter() | |
h := &http.Server{Addr: listenAt, Handler: r} | |
go func() { | |
log.Info("Serving on http://", listenAt) | |
if err := h.ListenAndServe(); err != nil { | |
log.Fatal(err) | |
} | |
}() | |
<-stop | |
log.Info("Stoping ...") | |
h.Shutdown(context.Background()) | |
log.Info("Bye :)") | |
} | |
func handler(w http.ResponseWriter, r *http.Request) { | |
time.Sleep(5 * time.Second) | |
log.Info("new request") | |
fmt.Fprintf(w, "Hola!") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment