Skip to content

Commit

Permalink
(BEDS-90) api: shut down server gracefully
Browse files Browse the repository at this point in the history
  • Loading branch information
guybrush committed Aug 12, 2024
1 parent 17e7af6 commit b2a9a89
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 8 deletions.
35 changes: 28 additions & 7 deletions backend/cmd/api/main.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package main

import (
"context"
"errors"
"flag"
"net"
"net/http"
Expand Down Expand Up @@ -69,12 +71,31 @@ func main() {
router.Use(ratelimit.HttpMiddleware)
}

srv := &http.Server{
Handler: router,
Addr: net.JoinHostPort(cfg.Frontend.Server.Host, cfg.Frontend.Server.Port),
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
var srv *http.Server
go func() {
srv = &http.Server{
Handler: router,
Addr: net.JoinHostPort(cfg.Frontend.Server.Host, cfg.Frontend.Server.Port),
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
log.Infof("serving on %s:%s", cfg.Frontend.Server.Host, cfg.Frontend.Server.Port)
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatal(err, "error serving", 0)
}
}()

utils.WaitForCtrlC()

log.Info("shutting down server")
if srv != nil {
shutDownCtx, cancelShutDownCtx := context.WithTimeout(context.Background(), 10*time.Second)
defer cancelShutDownCtx()
err = srv.Shutdown(shutDownCtx)
if err != nil {
log.Error(err, "error shutting down server", 0)
} else {
log.Info("server shut down")
}
}
log.Infof("Serving on %s:%s", cfg.Frontend.Server.Host, cfg.Frontend.Server.Port)
log.Fatal(srv.ListenAndServe(), "Error while serving", 0)
}
3 changes: 2 additions & 1 deletion backend/pkg/commons/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"sort"
"strconv"
"strings"
"syscall"
"time"
"unicode/utf8"

Expand Down Expand Up @@ -156,7 +157,7 @@ func fixUtf(r rune) rune {

func WaitForCtrlC() {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
signal.Notify(c, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
<-c
}

Expand Down

0 comments on commit b2a9a89

Please sign in to comment.