gin golang: what is gin.Context.Keys

huangapple go评论90阅读模式
英文:

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是每个请求的上下文的键值对。

这些键值对可以通过GetSet方法访问。后者的文档如下:

> Set用于为此上下文存储新的键值对。如果之前未使用过c.Keys,则它也会进行延迟初始化。

因此,该字段类似于context包的Context.WithValueContext.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.

huangapple
  • 本文由 发表于 2021年12月29日 03:22:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/70511604.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定