Skip to content

Commit

Permalink
Refactor usage of graceful from netlify-commons
Browse files Browse the repository at this point in the history
  • Loading branch information
mraerino committed Sep 6, 2019
1 parent e6d3d4d commit 6a564b2
Showing 1 changed file with 30 additions and 6 deletions.
36 changes: 30 additions & 6 deletions api/api.go
Expand Up @@ -3,7 +3,11 @@ package api
import (
"context"
"net/http"
"os"
"os/signal"
"regexp"
"syscall"
"time"

"github.com/jinzhu/gorm"
"github.com/sebest/xff"
Expand All @@ -15,7 +19,6 @@ import (
"github.com/go-chi/chi"
"github.com/netlify/gocommerce/conf"
gcontext "github.com/netlify/gocommerce/context"
"github.com/netlify/netlify-commons/graceful"
)

const (
Expand All @@ -38,13 +41,34 @@ type API struct {
// ListenAndServe starts the REST API.
func (a *API) ListenAndServe(hostAndPort string) {
log := logrus.WithField("component", "api")
server := graceful.NewGracefulServer(a.handler, log)
if err := server.Bind(hostAndPort); err != nil {
log.WithError(err).Fatal("http server bind failed")
server := &http.Server{
Addr: hostAndPort,
Handler: a.handler,
}

if err := server.Listen(); err != nil {
log.WithError(err).Fatal("http server listen failed")
done := make(chan struct{})
defer close(done)
go func() {
waitForTermination(log, done)
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
server.Shutdown(ctx)
}()

if err := server.ListenAndServe(); err != nil {
log.WithError(err).Fatal("API server failed")
}
}

// WaitForShutdown blocks until the system signals termination or done has a value
func waitForTermination(log logrus.FieldLogger, done <-chan struct{}) {
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt, syscall.SIGTERM, syscall.SIGINT)
select {
case sig := <-signals:
log.Infof("Triggering shutdown from signal %s", sig)
case <-done:
log.Infof("Shutting down...")
}
}

Expand Down

0 comments on commit 6a564b2

Please sign in to comment.