当上下文没有传递时,如何获取gin上下文?

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

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)
}

huangapple
  • 本文由 发表于 2022年9月8日 02:32:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/73640115.html
匿名

发表评论

匿名网友

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

确定