From d3987b5530c3fa3afbc5a62101bfc342149f859f Mon Sep 17 00:00:00 2001 From: Rafael Piovesan Date: Mon, 23 May 2022 08:23:58 -0300 Subject: [PATCH] feat(pkg): add httpserver pkg --- pkg/httpserver/fx.go | 41 ++++++++++++++++++++++++++++++++++++++++ pkg/httpserver/server.go | 17 +++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 pkg/httpserver/fx.go create mode 100644 pkg/httpserver/server.go diff --git a/pkg/httpserver/fx.go b/pkg/httpserver/fx.go new file mode 100644 index 0000000..f59b829 --- /dev/null +++ b/pkg/httpserver/fx.go @@ -0,0 +1,41 @@ +package httpserver + +import ( + "context" + "errors" + "net/http" + "time" + + "github.com/labstack/echo/v4" + "github.com/labstack/gommon/log" + "github.com/rafael-piovesan/go-rocket-ride/v2/pkg/config" + "go.uber.org/fx" +) + +func Invoke(lc fx.Lifecycle, e *echo.Echo, cfg config.Config) { + lc.Append(fx.Hook{ + OnStart: func(_ context.Context) error { + // Start server in a separate goroutine, this way when the server is shutdown "s.e.Start" will + // return promptly, and the call to "s.e.Shutdown" is the one that will wait for all other + // resources to be properly freed. If it was the other way around, the application would just + // exit without gracefully shutting down the server. + // For more details: https://medium.com/@momchil.dev/proper-http-shutdown-in-go-bd3bfaade0f2 + go func() { + if err := e.Start(cfg.ServerAddress); !errors.Is(err, http.ErrServerClosed) { + log.Fatalf("error running server: %v", err) + } + }() + return nil + }, + OnStop: func(ctx context.Context) error { + ctx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + if err := e.Shutdown(ctx); err != nil { + log.Errorf("error shutting down server: %v", err) + } else { + log.Info("server shutdown gracefully") + } + return nil + }, + }) +} diff --git a/pkg/httpserver/server.go b/pkg/httpserver/server.go new file mode 100644 index 0000000..4b8af95 --- /dev/null +++ b/pkg/httpserver/server.go @@ -0,0 +1,17 @@ +package httpserver + +import ( + "github.com/labstack/echo/v4" + "github.com/labstack/echo/v4/middleware" + "github.com/rafael-piovesan/go-rocket-ride/v2/pkg/config" +) + +func New(cfg config.Config) *echo.Echo { + e := echo.New() + e.HideBanner = true + + e.Use(middleware.Logger()) + e.Use(middleware.Recover()) + + return e +}