Skip to content

Instantly share code, notes, and snippets.

@beigna
Last active August 2, 2018 14:32
Show Gist options
  • Save beigna/f44fd1b127760d3869b2ebb7600b95fa to your computer and use it in GitHub Desktop.
Save beigna/f44fd1b127760d3869b2ebb7600b95fa to your computer and use it in GitHub Desktop.
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
}
@beigna
Copy link
Author

beigna commented Aug 2, 2018

package main

import (
	"fmt"
	"net/http"
	"time"

	"github.com/gorilla/mux"
	log "github.com/sirupsen/logrus"
)

func Routes() *mux.Router {
	r := mux.NewRouter()
	r.NotFoundHandler = http.HandlerFunc(notFound)
	r.HandleFunc("/info", info).Methods("GET")
	return r
}

func info(w http.ResponseWriter, r *http.Request) {
	start := time.Now()

	fmt.Fprintf(w, "Hola!")
	log.Infof("Req: %s - 200 - %s", r.URL.RequestURI(), time.Since(start))
}

func notFound(w http.ResponseWriter, r *http.Request) {
	start := time.Now()
	w.WriteHeader(http.StatusNotFound)
	fmt.Fprintf(w, "404 Not Found")
	log.Infof("Req: %s - 404 - %s", r.URL.RequestURI(), time.Since(start))
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment