Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(BEDS-90) api: shut down server gracefully #681

Merged
merged 1 commit into from
Aug 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading