2015-10-02 03:24:38 +02:00
|
|
|
---
|
|
|
|
title: Middleware
|
|
|
|
menu:
|
2015-10-08 22:54:31 +02:00
|
|
|
side:
|
2015-10-02 03:24:38 +02:00
|
|
|
parent: guide
|
2015-10-06 00:52:07 +02:00
|
|
|
weight: 4
|
2015-10-02 03:24:38 +02:00
|
|
|
---
|
|
|
|
|
|
|
|
Middleware is a function which is chained in the HTTP request-response cycle. Middleware
|
|
|
|
has access to the request and response objects which it utilizes to perform a specific
|
|
|
|
action, for example, logging every request.
|
|
|
|
|
|
|
|
### Logger
|
|
|
|
|
|
|
|
Logs each HTTP request with method, path, status, response time and bytes served.
|
|
|
|
|
|
|
|
*Example*
|
|
|
|
|
|
|
|
```go
|
|
|
|
e.Use(Logger())
|
|
|
|
|
|
|
|
// Output: `2015/06/07 18:16:16 GET / 200 13.238µs 14`
|
|
|
|
```
|
|
|
|
|
|
|
|
### BasicAuth
|
|
|
|
|
|
|
|
BasicAuth middleware provides an HTTP basic authentication.
|
|
|
|
|
|
|
|
- For valid credentials it calls the next handler in the chain.
|
|
|
|
- For invalid Authorization header it sends "404 - Bad Request" response.
|
|
|
|
- For invalid credentials, it sends "401 - Unauthorized" response.
|
|
|
|
|
|
|
|
*Example*
|
|
|
|
|
|
|
|
```go
|
|
|
|
e.Group("/admin")
|
|
|
|
e.Use(mw.BasicAuth(func(usr, pwd string) bool {
|
|
|
|
if usr == "joe" && pwd == "secret" {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}))
|
|
|
|
```
|
|
|
|
|
|
|
|
### Gzip
|
|
|
|
|
|
|
|
Gzip middleware compresses HTTP response using gzip compression scheme.
|
|
|
|
|
|
|
|
*Example*
|
|
|
|
|
|
|
|
```go
|
|
|
|
e.Use(mw.Gzip())
|
|
|
|
```
|
|
|
|
|
|
|
|
### Recover
|
|
|
|
|
2015-10-03 04:48:47 +02:00
|
|
|
Recover middleware recovers from panics anywhere in the chain and handles the
|
|
|
|
control to the centralized
|
|
|
|
[HTTPErrorHandler]({{< relref "guide/customization.md#http-error-handler">}}).
|
2015-10-02 03:24:38 +02:00
|
|
|
|
|
|
|
*Example*
|
|
|
|
|
|
|
|
```go
|
|
|
|
e.Use(mw.Recover())
|
|
|
|
```
|
|
|
|
|
2015-10-08 22:54:31 +02:00
|
|
|
### [Recipes](https://github.com/labstack/echo/tree/master/recipes/middleware)
|