Skip to content

Commit

Permalink
feat(pkg): add httpserver pkg
Browse files Browse the repository at this point in the history
  • Loading branch information
rafael-piovesan committed May 23, 2022
1 parent 174c5a2 commit d3987b5
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
41 changes: 41 additions & 0 deletions pkg/httpserver/fx.go
Original file line number Diff line number Diff line change
@@ -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
},
})
}
17 changes: 17 additions & 0 deletions pkg/httpserver/server.go
Original file line number Diff line number Diff line change
@@ -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
}

0 comments on commit d3987b5

Please sign in to comment.