github.com/AngusLu/go-swagger@v0.28.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 3 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 third point allows you to set the middleware for existing handler by its route and HTTP method. It can be done in the `configureAPI` function by calling `api.AddMiddlewareFor` method.
    50  
    51  ```go
    52  func configureAPI(api *operations.SomeAPI) http.Handler {
    53      api.AddMiddlewareFor('GET', '/', customMiddlewareFunc)
    54  }
    55  ```
    56  
    57  The global middleware is an excellent place to do things like panic handling, request logging or adding metrics.  While
    58  the plain middleware allows you to kind of filter this by request path without having to take care of routing. You also
    59  get access to the full context that the go-swagger toolkit uses throughout the lifecycle of a request.
    60  
    61  #### Add logging and panic handling
    62  
    63  A very common requirement for HTTP APIs is to include some form of logging. Another one is to handle panics from your
    64  API requests.  The example for a possible implementation of this uses [this community provided
    65  middleware](https://github.com/dre1080/recover) to catch panics.
    66  
    67  ```go
    68  func setupGlobalMiddleware(handler http.Handler) http.Handler {
    69    recovery := recover.New(&recover.Options{
    70      Log: log.Print,
    71    })
    72    return recovery(handler)
    73  }
    74  ```
    75  
    76  There are tons of middlewares out there, some are framework specific and some frameworks don't really use the plain
    77  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
    78  layer so you can still reuse middlewares. Of course nobody is stopping you to just implement your own middlewares.
    79  
    80  For example using interpose to integrate with [logrus](https://github.com/carbocation/interpose/blob/master/middleware/negronilogrus.go).
    81  
    82  ```go
    83  import (
    84    interpose "github.com/carbocation/interpose/middleware"
    85  )
    86  func setupGlobalMiddleware(handler http.Handler) http.Handler {
    87    logViaLogrus := interpose.NegroniLogrus()
    88    return logViaLogrus(handler)
    89  }
    90  ```
    91  
    92  And you can compose these middlewares into a stack using functions.
    93  
    94  ```go
    95  func setupGlobalMiddleware(handler http.Handler) http.Handler {
    96    handlePanic := recover.New(&recover.Options{
    97      Log: log.Print,
    98    })
    99  
   100    logViaLogrus := interpose.NegroniLogrus()
   101  
   102    return handlePanic(
   103      logViaLogrus(
   104        handler
   105      )
   106    )
   107  }
   108  ```
   109  
   110  #### Add rate limiting
   111  
   112  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
   113  API. To do so we could use [tollbooth](https://github.com/didip/tollbooth).
   114  
   115  ```go
   116  func setupMiddlewares(handler http.Handler) http.Handler {
   117    limiter := tollbooth.NewLimiter(1, time.Second)
   118    limiter.IPLookups = []string{"RemoteAddr", "X-Forwarded-For", "X-Real-IP"}
   119  	return tollbooth.LimitFuncHandler(handler)
   120  }
   121  ```
   122  
   123  And with this you've added rate limiting to your application.
   124  
   125  #### Add middleware to certain routes
   126  
   127  You can add standard `net/http` middleware to certain routes.
   128  
   129  ```go
   130  func myMiddleware(handler http.Handler) http.Handler {
   131      return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
   132      		// do some middleware logic here
   133      		handler.ServeHTTP(w, r)
   134      	})
   135  }
   136  
   137  ...
   138  api.AddMiddlewareFor("POST", "/example", myMiddleware)
   139  ```