登录
首页 >  Golang >  Go问答

当杜松子酒没有传入时获取上下文?

来源:stackoverflow

时间:2024-04-05 21:54:28 331浏览 收藏

有志者,事竟成!如果你在学习Golang,那么本文《当杜松子酒没有传入时获取上下文?》,就很适合你!文章讲解的知识点主要包括,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

刚接触 go/gin,我试图了解如何在从第 3 方库收到回调的情况下访问 gin 上下文。

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?

}

gin 是否在请求对象的某处放置了对自身的引用?

如果没有,我应该自己在请求对象中存储一个引用吗?


正确答案


您可以在请求上下文中传递它:

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

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>