Skip to content

Commit

Permalink
chore(server): Gracefully shutting down the server (#60)
Browse files Browse the repository at this point in the history
Gracefully shutting down the server
  • Loading branch information
Jacobbrewer1 authored Feb 13, 2024
1 parent 53fc9c2 commit 7c57476
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 4 deletions.
6 changes: 5 additions & 1 deletion cmd/summary/cmd_serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"context"
"errors"
"flag"
"fmt"
"log/slog"
Expand Down Expand Up @@ -99,7 +100,10 @@ func (s *serveCmd) Execute(ctx context.Context, f *flag.FlagSet, _ ...interface{

// Start the server in a goroutine, so we can listen for the context to be done.
go func(srv *http.Server) {
if err := srv.ListenAndServe(); err != nil {
err := srv.ListenAndServe()
if errors.Is(err, http.ErrServerClosed) {
slog.Debug("Server closed gracefully")
} else if err != nil {
slog.Error("Error serving requests", slog.String(logging.KeyError, err.Error()))
}
}(srv)
Expand Down
17 changes: 16 additions & 1 deletion cmd/summary/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ package main
import (
"context"
"flag"
"log/slog"
"os"
"os/signal"
"syscall"

"github.com/google/subcommands"
)
Expand All @@ -24,6 +27,18 @@ func main() {
subcommands.Register(new(purgeCmd), "")

flag.Parse()
ctx := context.Background()

// Listen for ctrl+c and kill signals
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

go func() {
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt, syscall.SIGTERM)
got := <-sig
slog.Debug("Received signal, shutting down", slog.String("signal", got.String()))
cancel()
}()

os.Exit(int(subcommands.Execute(ctx)))
}
2 changes: 1 addition & 1 deletion pkg/dataaccess/db_mongo.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ func connectMongoDB(ctx context.Context) {
slog.Debug("Found MongoDB URI in environment")
} else {
// Missing environment variable.
slog.Error("No MongoDB URI provided in environment")
slog.Error(fmt.Sprintf("No %s environment variable provided", envDbConnStr))
os.Exit(1)
}

Expand Down
2 changes: 1 addition & 1 deletion pkg/dataaccess/db_mysql.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ func connectMysql() {
slog.Debug("Found MySQL URI in environment")
} else {
// Missing environment variable.
slog.Error("No MongoDB URI provided in environment")
slog.Error(fmt.Sprintf("No %s environment variable provided", envDbConnStr))
os.Exit(1)
}

Expand Down

0 comments on commit 7c57476

Please sign in to comment.