I have a Context
struct that is used for the Application Context. The ConfigureRouter
function receives the context as a parameter and sets the global variable c
so middleware in the same file can use it.
var c *core.Context
func ConfigureRouter(ctx *core.Context, router *httprouter.Router) {
c = ctx //make context available in all middleware
router.POST("/v1/tokens/create", token.Create) //using httprouter
}
The one route listed above calls token.Create
( from the token package which is a sub-directory) but it needs the context too.
//token/token.go
func Create(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
//Help! I need the context to do things
}
How can I pass the context to the token package?
You can redefine your Create function as a function that returns the handler function:
func Create(ctx *core.Context) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
// Now you have the context to do things
}
}
Where httprouter.Handle
is a func type defined by httprouter to be type Handle func(http.ResponseWriter, *http.Request, Params)
.
And then you would use it like this in ConfigureRouter
:
func ConfigureRouter(ctx *core.Context, router *httprouter.Router) {
router.POST("/v1/tokens/create", token.Create(ctx))
}