-
Notifications
You must be signed in to change notification settings - Fork 15
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
174c5a2
commit d3987b5
Showing
2 changed files
with
58 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
}, | ||
}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |