Skip to content

Commit 731d3e6

Browse files
committed
Merge pull request #175 from manyminds/documentation-middleware-context
document middleware/context usage
2 parents 0d16cbb + 7259947 commit 731d3e6

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

README.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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
537538
to check all your other structs and if it references the one for that you are implementing `FindAll`, check for the
538539
query 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

Comments
 (0)