github.com/kaisawind/go-swagger@v0.19.0/docs/use/middleware.md (about) 1 # Build Your Own middleware 2 3 Go-swagger chose the golang `net/http` package as base abstraction. That means that for _any_ supported transport by the toolkit you can reuse _any_ middleware existing middlewares that following the stdlib middleware pattern. 4 5 <!--more--> 6 7 There are several projects providing middleware libraries for weaving all kinds of functionality into your request handling. None of those things are the job of go-swagger, go-swagger just serves your specs. 8 9 The server takes care of a number of things when a request arrives: 10 11 * routing 12 * authentication 13 * input validation 14 * content negotiation 15 * parameter and body binding 16 17 If you're unfamiliar with the concept of golang net/http middlewares you can read up on it here: 18 [Making and Using HTTP Middleware](http://www.alexedwards.net/blog/making-and-using-middleware) 19 20 Besides serving the swagger specification as an API, the toolkit also serves the actual swagger specification document. 21 The convention is to use the `/swagger.json` location for serving up the specification document, so we serve the 22 specification at that path. 23 24 ### Add middleware 25 26 The generated server allows for 2 extension points to inject middleware in its middleware chain. These have to do with 27 the lifecycle of a request. You can find those hooks in the configure_xxx_api.go file. 28 29 The first one is to add middleware all the way to the top of the middleware stack. To do this you add them in the 30 `setupGlobalMiddleware` method. This middleware applies to everything in the go-swagger managed API. 31 32 ```go 33 func setupGlobalMiddleware(handler http.Handler) http.Handler { 34 return handler 35 } 36 ``` 37 38 The second extension point allows for middleware to be injected right before actually handling a matched request. 39 This excludes the swagger.json document from being affected by this middleware though. This extension point makes the 40 middlewares execute right after routing but right before authentication, binding and validation. You add middlewares 41 to this point by editing the `setupMiddlewares` method in configure_xxx_api.go 42 43 ```go 44 func setupMiddlewares(handler http.Handler) http.Handler { 45 return handler 46 } 47 ``` 48 49 The global middleware is an excellent place to do things like panic handling, request logging or adding metrics. While 50 the plain middleware allows you to kind of filter this by request path without having to take care of routing. You also 51 get access to the full context that the go-swagger toolkit uses throughout the lifecycle of a request. 52 53 #### Add logging and panic handling 54 55 A very common requirement for HTTP APIs is to include some form of logging. Another one is to handle panics from your 56 API requests. The example for a possible implementation of this uses [this community provided 57 middleware](https://github.com/dre1080/recover) to catch panics. 58 59 ```go 60 func setupGlobalMiddleware(handler http.Handler) http.Handler { 61 recovery := recover.New(&recover.Options{ 62 Log: log.Print, 63 }) 64 return recovery(handler) 65 } 66 ``` 67 68 There are tons of middlewares out there, some are framework specific and some frameworks don't really use the plain 69 vanilla golang net/http as base abstraction. For those you can use a project like [interpose](https://github.com/carbocation/interpose) that serves as an adapter 70 layer so you can still reuse middlewares. Of course nobody is stopping you to just implement your own middlewares. 71 72 For example using interpose to integrate with [logrus](https://github.com/carbocation/interpose/blob/master/middleware/negronilogrus.go). 73 74 ```go 75 import ( 76 interpose "github.com/carbocation/interpose/middleware" 77 ) 78 func setupGlobalMiddleware(handler http.Handler) http.Handler { 79 logViaLogrus := interpose.NegroniLogrus() 80 return logViaLogrus(handler) 81 } 82 ``` 83 84 And you can compose these middlewares into a stack using functions. 85 86 ```go 87 func setupGlobalMiddleware(handler http.Handler) http.Handler { 88 handlePanic := recover.New(&recover.Options{ 89 Log: log.Print, 90 }) 91 92 logViaLogrus := interpose.NegroniLogrus() 93 94 return handlePanic( 95 logViaLogrus( 96 handler 97 ) 98 ) 99 } 100 ``` 101 102 #### Add rate limiting 103 104 You can also add rate limiting in a similar way. Let's say we just want to rate limit the valid requests to our swagger 105 API. To do so we could use [tollbooth](https://github.com/didip/tollbooth). 106 107 ```go 108 func setupMiddlewares(handler http.Handler) http.Handler { 109 limiter := tollbooth.NewLimiter(1, time.Second) 110 limiter.IPLookups = []string{"RemoteAddr", "X-Forwarded-For", "X-Real-IP"} 111 return tollbooth.LimitFuncHandler(handler) 112 } 113 ``` 114 115 And with this you've added rate limiting to your application.