英文:
gin golang: what is gin.Context.Keys
问题
我正在使用go-gin框架中的context.GetBool
方法(这里)来处理一些查询参数。但是它没有按照预期工作,我认为Context.Keys
没有被查询参数填充。
所以我的问题是:gin.Context.Keys
是什么,当发起请求时应该如何填充它?
PS:这个问题已经在这里提出过,但没有得到正确的答案。
英文:
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.
答案1
得分: 2
tl;dr Keys
字段是支持Gin的Context实现context.Context
接口的请求范围键值对载体。
> 我认为Context.Keys不会由查询参数填充。
正确。Context.Keys
与查询参数无关。查询参数可以通过Context.Query
获取。
关于Keys
,结构字段的文档中写道:
> Keys是每个请求的上下文的键值对。
> Set用于为此上下文存储新的键值对。如果之前未使用过c.Keys,则它也会进行延迟初始化。
因此,该字段类似于context
包的Context.WithValue
和Context.Value
,即请求范围的参数。Gin的Context Keys
是存储原始键值对的导出映射。GetBool
等方法是方便的,因为你不需要自己进行类型断言来获取interface{}
值。
与其他Web框架不同,Gin的Context不包装context.Context
值(除了c.Request.Context
),而是直接实现了该接口。这包括Value
方法本身,它也访问底层的Keys
字段。
顺便提一下,与标准库的context
实现的一个重要区别是,context.Context
接受interface{}
键,而Gin的Context只接受string
键。
英文:
tl;dr The Keys
field is what backs up Gin's Context implementation of context.Context
interface as a request-scoped key/value carrier.
<hr>
> 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论