将用户存储在上下文中还是其他地方?

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

Store users in context or somewhere else?

问题

我在寻找最佳方法来思考问题,但是遇到了困难。我想知道在用户通过某种类型的中间件(如BasicAuthJWT)进行身份验证后,应该如何处理用户。

我是否应该将所有相关的用户字段作为值存储在上下文中?如果我将它们存储在上下文中,那么我是否需要一个特殊的函数来提取它们?(该函数将使用用户定义的上下文键类型来检索并将其类型转换回正确的结构体)

我可以想出一些可行的方法,但不确定是否是最合理的方法。

英文:

I am having a hard time finding out if I am thinking about things in the best way. I want to know what to do with a user after they have been authenticated through some type of middleware, either BasicAuth or JWT.

Should I store all the relevant user fields in the context as a value? If I store them in the context then do I need a special function to pull them out? (which would use a user defined contextKey type to retrieve and convert its type back to the proper struct)

I can come up with something that works, but IDK if it is the most reasonable way to go about it.

答案1

得分: 0

是的,context.Context 是专门用于请求范围变量的,还有其他功能。(请注意,每个请求都是独立的,所以不适合存储需要在请求之间访问的数据;对于这种情况,你应该考虑使用某种会话机制)

context.Value(key interface{}) interface{} 是用于从上下文中检索值的接口函数。

英文:

Yes, context.Context is specifically for request scoped variables, among other things. (Notice, per request, so not suitable for storing data you mean to access between requests; for that you should consider some sort of session mechanism)

the context.Value(key interface{}) interface{} interface function is how you retrieve values back out of the context.

huangapple
  • 本文由 发表于 2017年4月24日 19:15:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/43586607.html
匿名

发表评论

匿名网友

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

确定