英文:
Getting the gin context when it's not passed in?
问题
你好!根据你提供的代码,你想知道如何在从第三方库获取回调时访问gin上下文。在gin中,上下文(Context)是通过请求(Request)对象传递的。gin并没有在请求对象中直接放置对自身的引用。如果你需要在回调函数中获取gin上下文,你可以将gin上下文作为自定义请求头或请求参数的一部分传递给第三方库。然后,在回调函数中,你可以从请求对象中提取这些自定义头或参数,并使用它们来获取gin上下文。希望这可以帮助到你!
英文:
New to go/gin and I am trying to understand how to access the gin context in a situation where you are getting a callback from a 3rd party library.
gin.GET("/someurl", someHandler)
...
func someHandler(c *gin.Context) {
// pass request off to third party lib that will call our GetSession() method later
// the third party does not take a gin context, only http request and writer
3rdpartylib.HandleRequest(c.Writer, c.Request)
}
func (t *THINGY) GetSession(w http.ResponseWriter, r *http.Request) {
// How do I get the gin context for the request back?
}
Does gin put a reference to itself in the request object somewhere?
If not, should I stash a reference in the request object myself?
答案1
得分: 0
你可以将其传递给请求上下文:
newCtx := context.WithValue(Request.Context(), "session", c)
3rdpartylib.HandleRequest(c.Writer, c.Request.WithContext(newCtx))
...
func (t *THINGY) GetSession(w http.ResponseWriter, r *http.Request) {
c := r.Context().Value("session").(*gin.Context)
}
英文:
You can pass it in the request context:
newCtx:=context.WithValue(Request.Context(),"session",c)
3rdpartylib.HandleRequest(c.Writer, c.Request.WithContext(newCtx))
...
func (t *THINGY) GetSession(w http.ResponseWriter, r *http.Request) {
c:=r.Context().Value("session").(*gin.Context)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论