mirror of
https://github.com/nais/wonderwall.git
synced 2026-05-21 15:52:54 +00:00
refactor: clean up main
This commit is contained in:
54
pkg/server/server.go
Normal file
54
pkg/server/server.go
Normal file
@@ -0,0 +1,54 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/nais/wonderwall/pkg/config"
|
||||
)
|
||||
|
||||
func Start(cfg *config.Config, r chi.Router) error {
|
||||
server := http.Server{
|
||||
Addr: cfg.BindAddress,
|
||||
Handler: r,
|
||||
}
|
||||
|
||||
serverCtx, serverStopCtx := context.WithCancel(context.Background())
|
||||
|
||||
sig := make(chan os.Signal, 1)
|
||||
signal.Notify(sig, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
|
||||
go func() {
|
||||
<-sig
|
||||
|
||||
shutdownCtx, shutdownStopCtx := context.WithTimeout(serverCtx, 20*time.Second)
|
||||
|
||||
go func() {
|
||||
<-shutdownCtx.Done()
|
||||
if shutdownCtx.Err() == context.DeadlineExceeded {
|
||||
log.Fatal("graceful shutdown timed out.. forcing exit.")
|
||||
}
|
||||
}()
|
||||
|
||||
err := server.Shutdown(shutdownCtx)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
shutdownStopCtx()
|
||||
serverStopCtx()
|
||||
}()
|
||||
|
||||
err := server.ListenAndServe()
|
||||
if err != nil && err != http.ErrServerClosed {
|
||||
return err
|
||||
}
|
||||
|
||||
<-serverCtx.Done()
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user