I was tring to use the method context.GetBool
(here) from the go-gin framework with some query params.
It doesn't work as excepted and I think the Context.Keys
is not populated by query params.
So my question is: what is gin.Context.Keys
, and how should it be populated when making a request ?
PS: the question was already asked here, but left without a proper answer.
CodePudding user response:
tl;dr The Keys
field is what backs up Gin's Context implementation of context.Context
interface as a request-scoped key/value carrier.
I think the Context.Keys is not populated by query params.
Correct. Context.Keys
is unrelated to query params. Query params are available with Context.Query
.
About Keys
instead, the document on the struct field reads:
Keys is a key/value pair exclusively for the context of each request.
And these key/value pairs are accessible with Get
and Set
. The docs of this latter one are:
Set is used to store a new key/value pair exclusively for this context. It also lazy initializes c.Keys if it was not used previously.
Hence the field is similar to context
package's Context.WithValue
and Context.Value
, e.g. request-scoped parameters. Gin's Context Keys
is the exported map that stores the raw key/value pairs. The methods such as GetBool
are convenience, in that you don't have to type-assert the interface{}
values yourself.
Unlike other web frameworks, Gin's Context does not wrap a context.Context
value (except for c.Request.Context
), instead it directly implements the interface. This includes the Value
method itself, which also accesses the underlying Keys
field.
By the way, an important difference from the standard lib context
implementation is that context.Context
accepts interface{}
keys, whereas Gin's Context accepts only string
keys.