英文:
How to access Request Specific Data in Go?
问题
我有一个用Go编写的API,并且我正在使用gin-gonic框架来实现我的端点。我正在遵循清晰架构的原则,这意味着我的整个应用程序被划分为多个层,包括控制器(Controller)、服务(Service)、存储库(Repository)和会话(Session)。端点由auth0进行安全保护,并且验证是在gin中间件中进行的。在中间件中,我可以从JWT中提取主题(在标头中设置)。
现在,这是我的问题。我想在我的查询中使用这个主题值。我想知道是否可以将主题(sub)存储在上下文中,并在代码的其他部分中使用它,而无需传递上下文。这种可能吗?还是我只需更新所有的函数,并在所有下游调用中添加一个新的参数"Sub"?
我在暗示使用一种全局变量的方式来访问请求特定的数据(来自JWT令牌的SUB)。我知道这是一种不好的做法,我只是想知道是否有其他方法可以实现这一点,而不是传递请求特定的数据?任何帮助都将不胜感激。
英文:
I have an API written in go and I am using the gin-gonic framework to implement my endpoints. I am following clean architecture for my project which means that my entire application is divided into multiple layers namely - Controller, Service, Repository, And Session. The endpoints are secured by auth0 and the validation is carried out in a gin middleware. In the middleware I can extract the Subject from the JWT (Set in the header)
Now, here's my question. I want to use this subject value in my queries. I was wondering if I can store the Subject (sub) in the context and use it in other parts of my code WITHOUT PASSING CONTEXT AROUND. Is this possible? Or do I simply have to update all my functions and add a new parameter "Sub" to all downstream calls?
I am alluding to using a Global Variable of sorts to access Request Specific Data (SUB from the JWT token). I know it's a bad practice- I am just wondering if there is any other way to accomplish this other than passing around request specific data? Any help is appreciated.
答案1
得分: 1
这真的是上下文的全部要点 - 它存在的目的就是保存这些内容并在链条中传递。这很重要,因为你希望将其限定在请求范围内 - 如果你开始使用全局变量,可能会遇到多个请求同时操作相同数据而导致冲突的问题。同样,如果令牌在请求之间被作废,也会出现问题。
如果你的身份验证中间件在查询之前运行(听起来是这样),那么只需要让它以你满意的方式将主题放入上下文中即可。
英文:
It is really the whole point of the context - it exists to hold these kinds of things and to be passed around the chain. It's important because you want to keep it scoped to the request -- if you start using globals you could run into issues where you get contention because multiple requests are messing with the same data. Likewise if the token was invalidated between requests.
If your authentication middleware runs before your query (which it sounds like it does) then it should be simply a matter of having it put the subject in the context in a way you're happy with.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论