go-martini / martini

Classy web framework for Go
martini.codegangsta.io
MIT License
11.63k stars 1.1k forks source link

Using context.Context in Handlers #404

Closed aedenj closed 7 years ago

aedenj commented 7 years ago

I'm relatively new to Go and have inherited a few services written in it using Martini. I'd like to use the context.Context in Go 1.7 for the typical use case of storing a user id. It's unclear to me how i can store the user id and have it available to other handlers. Any help would be appreciated.

erizocosmico commented 7 years ago

You can inject it in a middleware:

func myCtxMiddleware(c martini.Context) {
        c.Map(context.Background())
}

and then get the context like this in your handlers and subsequent middlewares:

func Handler(ctx context.Context) {
        // use ctx
}

Also, if your intention is to just keep a few values that you know beforehand you can avoid using context.Context and just use your custom struct directly.

type AppCtx struct {
        UserID int64
        MoreStuff interface{}
}

func Middleware(c martini.Context) {
        c.Map(&AppCtx{UserID: foo})
}

func Handler(ctx *AppCtx) {
        // use ctx
}