github.com/System-Glitch/goyave/v2@v2.10.3-0.20200819142921-51011e75d504/docs_src/src/guide/basics/middleware.md (about) 1 --- 2 meta: 3 - name: "og:title" 4 content: "Middleware - Goyave" 5 - name: "twitter:title" 6 content: "Middleware - Goyave" 7 - name: "title" 8 content: "Middleware - Goyave" 9 --- 10 11 # Middleware 12 13 [[toc]] 14 15 ## Introduction 16 17 Middleware are handlers executed before the controller handler. They are a convenient way to filter, intercept or alter HTTP requests entering your application. For example, middleware can be used to authenticate users. If the user is not authenticated, a message is sent to the user even before the controller handler is reached. However, if the user is authenticated, the middleware will pass to the next handler. Middleware can also be used to sanitize user inputs, by trimming strings for example, to log all requests into a log file, to automatically add headers to all your responses, etc. 18 19 Writing middleware is as easy as writing standard handlers. In fact, middleware are handlers, but they have an additional responsibility: when they are done, the may or may not pass to the next handler, which is either another middleware or a controller handler. 20 21 ## Writing middleware 22 23 Each middleware is written in its own file inside the `http/middleware` directory. A `Middleware` is a function returning a `Handler`. 24 25 ::: tip 26 `goyave.Middleware` is an alias for `func(goyave.Handler) goyave.Handler` 27 ::: 28 29 **Example:** 30 ``` go 31 func MyCustomMiddleware(next goyave.Handler) goyave.Handler { 32 return func(response *goyave.Response, request *goyave.Request) { 33 // Do something 34 next(response, request) // Pass to the next handler 35 } 36 } 37 ``` 38 39 When implementing middleware, keep in mind that the request **has not been validated yet**! Manipulating unvalidated data can be dangerous, especially in form-data where the data types are not converted by the validator yet. In middleware, you should always check if the request has been parsed correctly before trying to access its data: 40 ``` go 41 if request.Data != nil { 42 // Parsing OK 43 } 44 ``` 45 46 If you want your middleware to stop the request and respond immediately before reaching the controller handler, simply don't call the `next` handler. In the following example, consider that you developed a custom authentication system: 47 ``` go 48 func CustomAuthentication(next goyave.Handler) goyave.Handler { 49 return func(response *goyave.Response, request *goyave.Request) { 50 if !auth.Check(request) { 51 response.Status(http.StatusUnauthorized) 52 return 53 } 54 55 next(response, request) 56 } 57 } 58 ``` 59 60 ::: tip 61 When a middleware stops a request, following middleware are **not** executed neither. 62 ::: 63 64 ## Applying Middleware 65 66 When your middleware is ready, you will need to apply it to a router or a specific route. When applying a middleware to a router, all routes and subrouters will execute this middleware when matched. 67 68 ```go 69 router.Middleware(middleware.MyCustomMiddleware) 70 71 router.Get("/products", product.Index).Middleware(middleware.MyCustomMiddleware) 72 ``` 73 74 ## Built-in middleware 75 76 Built-in middleware is located in the `middleware` package. 77 ``` go 78 import "github.com/System-Glitch/goyave/v2/middleware" 79 ``` 80 81 ### DisallowNonValidatedFields 82 83 DisallowNonValidatedFields validates that all fields in the request are validated by the RuleSet. The middleware stops the request and sends "422 Unprocessable Entity" and an error message if the user has sent non-validated field(s). Fields ending with `_confirmation` are ignored. 84 85 If the body parsing failed, this middleware immediately passes to the next handler. **This middleware shall only be used with requests having a rule set defined.** 86 87 The returned error message can be customized using the entry `disallow-non-validated-fields` in the `locale.json` language file. 88 89 ```go 90 router.Middleware(middleware.DisallowNonValidatedFields) 91 ``` 92 93 ### Trim 94 95 <p><Badge text="Since v2.0.0"/></p> 96 97 Trim removes all leading and trailing white space from string fields. 98 99 For example, `" \t trimmed\n \t"` will be transformed to `"trimmed"`. 100 101 ```go 102 router.Middleware(middleware.Trim) 103 ``` 104 105 ### Gzip 106 107 <p><Badge text="Since v2.7.0"/></p> 108 109 Gzip compresses HTTP responses with default compression level for clients that support it via the `Accept-Encoding` header. 110 111 ```go 112 router.Middleware(middleware.Gzip()) 113 ``` 114 115 The compression level can be specified using `GzipLevel(level)`. The compression level should be `gzip.DefaultCompression`, `gzip.NoCompression`, or any integer value between `gzip.BestSpeed` and `gzip.BestCompression` inclusive. `gzip.HuffmanOnly` is also available. 116 117 ``` go 118 router.Middleware(middleware.GzipLevel(gzip.BestCompression)) 119 ```