Skip to content
This repository has been archived by the owner on Sep 13, 2023. It is now read-only.

Commit

Permalink
Merge pull request #289 from go-dummy/feat/graceful-shutdown
Browse files Browse the repository at this point in the history
feat: add graceful shutdown
  • Loading branch information
sashamelentyev authored Jan 28, 2022
2 parents 8187e83 + e073aca commit 11112b1
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 2 deletions.
24 changes: 23 additions & 1 deletion cmd/dummy/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,14 @@ package main

import (
"context"
"errors"
"flag"
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"time"

"github.com/cristalhq/acmd"

Expand Down Expand Up @@ -49,7 +54,24 @@ func run() error {
h := server.NewHandlers(api, l)
s := server.NewServer(cfg.Server, l, h)

return s.Run()
go func() {
if err := s.Run(); !errors.Is(err, http.ErrServerClosed) {
l.Logger.Err(err).Msg("run server")
}
}()

interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt, syscall.SIGTERM)

x := <-interrupt
l.Info().Msgf("received `%v`", x)

const timeout = 5 * time.Second

ctx, cancelFunc := context.WithTimeout(ctx, timeout)
defer cancelFunc()

return s.Stop(ctx)
},
},
}
Expand Down
2 changes: 1 addition & 1 deletion internal/api/build_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ package api_test

import (
"fmt"
"github.com/go-dummy/openapi"
"strconv"
"testing"

"github.com/go-dummy/openapi"
"github.com/stretchr/testify/require"

"github.com/go-dummy/dummy/internal/api"
Expand Down
5 changes: 5 additions & 0 deletions internal/server/server.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package server

import (
"context"
"net/http"

"github.com/go-dummy/dummy/internal/config"
Expand Down Expand Up @@ -47,3 +48,7 @@ func (s *Server) Run() error {

return nil
}

func (s *Server) Stop(ctx context.Context) error {
return s.Server.Shutdown(ctx)
}

0 comments on commit 11112b1

Please sign in to comment.