Optinally pass context factory alongside context
arnaudbriche opened this issue · 1 comments
arnaudbriche commented
Hi,
I have this use case where I need to pass some pointers to data structure to each new instanciated context; these structures mostly contain pointers to services (datastore, search...) that are created at application startup. Problem is: I don't see any hook I could use to pass these structures to newly created context.
I though maybe it would be useful for me and others to be able to pass a context factory (func() *Context) to the router at creation time. With this, I could do somethinh like:
type Context struct {
Search *SearchService
}
...
search := NewSearchService(...)
router := web.New(Context{}, func() *Context {
return &Context{Search: search}
})
arnaudbriche commented
Well, actually, the solution was to use a middleware:
type Context struct {
Search *SearchService
}
...
search := NewSearchService(...)
router := web.New(Context{})
router.Middleware(func(ctx *Context, resp web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) {
ctx.Search = search
next(resp, req)
})