Last active
August 2, 2018 14:32
-
-
Save beigna/f44fd1b127760d3869b2ebb7600b95fa to your computer and use it in GitHub Desktop.
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" | |
"strconv" | |
"syscall" | |
"time" | |
log "github.com/sirupsen/logrus" | |
) | |
func init() { | |
log.SetOutput(os.Stdout) | |
} | |
func main() { | |
log.Infof("Starting server (PID %d) ...", os.Getpid()) | |
stop := make(chan os.Signal) | |
signal.Notify(stop, syscall.SIGTERM) | |
signal.Notify(stop, syscall.SIGINT) | |
shutdownWait, err := strconv.Atoi(getEnv("SHUTDOWN_WAIT", "60")) | |
if err != nil { | |
log.Fatal("SHUTDOWN_WAIT EnVar must be Integer") | |
} | |
listenAt := fmt.Sprintf("%s:%s", getEnv("HOST", "127.0.0.1"), getEnv("PORT", "8000")) | |
r := Routes() | |
h := &http.Server{Addr: listenAt, Handler: r} | |
go func() { | |
log.Info("Serving on http://", listenAt) | |
if err := h.ListenAndServe(); err != nil { | |
log.Warning(err) | |
} | |
}() | |
<-stop | |
log.Infof("Shutting down server (waiting until %ds for requests get done) ...", shutdownWait) | |
ctx, _ := context.WithTimeout(context.Background(), time.Duration(shutdownWait)*time.Second) | |
h.Shutdown(ctx) | |
log.Info("Server gracefully stopped :)") | |
} | |
func getEnv(key, fallback string) string { | |
value, exists := os.LookupEnv(key) | |
if exists { | |
return value | |
} | |
return fallback | |
} |
Author
beigna
commented
Aug 2, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment