diff --git a/cookbook/timeouts/server.go b/cookbook/timeouts/server.go new file mode 100644 index 00000000..fd7c9476 --- /dev/null +++ b/cookbook/timeouts/server.go @@ -0,0 +1,28 @@ +package main + +import ( + "net/http" + "time" + + "github.com/labstack/echo/v4" + "github.com/labstack/echo/v4/middleware" +) + +func main() { + // Echo instance + e := echo.New() + + // Middleware + e.Use(middleware.TimeoutWithConfig(middleware.TimeoutConfig{ + Timeout: 5 * time.Second, + })) + + // Route => handler + e.GET("/", func(c echo.Context) error { + time.Sleep(10 * time.Second) + return c.String(http.StatusOK, "Hello, World!\n") + }) + + // Start server + e.Logger.Fatal(e.Start(":1323")) +} diff --git a/website/content/cookbook/timeouts.md b/website/content/cookbook/timeouts.md new file mode 100644 index 00000000..845d9f54 --- /dev/null +++ b/website/content/cookbook/timeouts.md @@ -0,0 +1,17 @@ ++++ +title = "Timeouts Recipe" +description = "Timeout recipe for Echo" +[menu.main] + name = "Timeouts" + parent = "cookbook" ++++ + +`server.go` + +{{< embed "timeouts/server.go" >}} + +## [Source Code]({{< source "timeouts" >}}) + +## Maintainers + +- [ilijamt](https://github.com/ilijamt) diff --git a/website/content/middleware/timeout.md b/website/content/middleware/timeout.md new file mode 100644 index 00000000..1c4a31ec --- /dev/null +++ b/website/content/middleware/timeout.md @@ -0,0 +1,63 @@ ++++ +title = "Timeout Middleware" +description = "Timeout middleware for Echo" +[menu.main] + name = "Timeout" + parent = "middleware" ++++ + +Timeout middleware is used to timeout at a long running operation within a predefined period. + +*Usage* + +`e.Use(middleware.Timeout())` + +## Custom Configuration + +*Usage* + +```go +e := echo.New() +e.Use(middleware.TimeoutWithConfig(middleware.TimeoutConfig{ + Skipper: Skipper, + ErrorHandler: func(err error, e echo.Context) error { + // you can handle your error here, the returning error will be + // passed down the middleware chain + return err + }, + Timeout: 30*time.Second, +})) +``` + +## Configuration + +```go +// TimeoutConfig defines the config for Timeout middleware. +TimeoutConfig struct { + // Skipper defines a function to skip middleware. + Skipper Skipper + // ErrorHandler defines a function which is executed for a timeout + // It can be used to define a custom timeout error + ErrorHandler TimeoutErrorHandlerWithContext + // Timeout configures a timeout for the middleware, defaults to 0 for no timeout + Timeout time.Duration +} +``` + +*TimeoutErrorHandlerWithContext* is responsible for handling the errors when a timeout happens +```go +// TimeoutErrorHandlerWithContext is an error handler that is used +// with the timeout middleware so we can handle the error +// as we see fit +TimeoutErrorHandlerWithContext func(error, echo.Context) error +``` + +*Default Configuration* + +```go +DefaultTimeoutConfig = TimeoutConfig{ + Skipper: DefaultSkipper, + Timeout: 0, + ErrorHandler: nil, +} +```