@@ -37,6 +37,7 @@ go get github.com/manyminds/api2go/jsonapi
3737 - [ Using Pagination] ( #using-pagination )
3838 - [ Fetching related IDs] ( #fetching-related-ids )
3939 - [ Fetching related resources] ( #fetching-related-resources )
40+ - [ Using middleware] ( #using-middleware )
4041- [ Tests] ( #tests )
4142
4243## Examples
@@ -537,6 +538,35 @@ So if you implement the `FindAll` method, do not forget to check for all possibl
537538to check all your other structs and if it references the one for that you are implementing ` FindAll ` , check for the
538539query Paramter and only return comments that belong to it. In this example, return the comments for the Post.
539540
541+ ### Using middleware
542+ Using middlewares can always be useful. We provide a custom ` APIContext ` with
543+ a [ context] ( https://godoc.org/golang.org/x/net/context ) implementation that you
544+ can use if you for example need to check if a user is properly authenticated
545+ before a request reaches the api2go routes.
546+
547+ You can either use our struct or implement your own with the ` APIContexter `
548+ interface
549+
550+ ``` go
551+ type APIContexter interface {
552+ context.Context
553+ Set (key string , value interface {})
554+ Get (key string ) (interface {}, bool )
555+ Reset ()
556+ }
557+ ```
558+
559+ If you implemented your own ` APIContexter ` , don't forget to define
560+ a ` APIContextAllocatorFunc ` and set it with ` func (api *API) SetContextAllocator(allocator APIContextAllocatorFunc) `
561+
562+ But in most cases, this is not needed.
563+
564+ To use a middleware, it is needed to implement our
565+ ` type HandlerFunc func(APIContexter, http.ResponseWriter, *http.Request) ` . A ` HandlerFunc ` can then be
566+ registered with ` func (api *API) UseMiddleware(middleware ...HandlerFunc) ` . You can either pass one or many middlewares
567+ that will be executed in order before any other api2go routes. Use this to set up database connections, user authentication
568+ and so on.
569+
540570## Tests
541571
542572``` sh
0 commit comments