英文:
Store users in context or somewhere else?
问题
我在寻找最佳方法来思考问题,但是遇到了困难。我想知道在用户通过某种类型的中间件(如BasicAuth
或JWT
)进行身份验证后,应该如何处理用户。
我是否应该将所有相关的用户字段作为值存储在上下文中?如果我将它们存储在上下文中,那么我是否需要一个特殊的函数来提取它们?(该函数将使用用户定义的上下文键类型来检索并将其类型转换回正确的结构体)
我可以想出一些可行的方法,但不确定是否是最合理的方法。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论