在Golang中,可以将userID存储在HTTP结构体中。

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

Golang - store userID in http struct

问题

我需要将userID存储在http.ResponseWriter或req *http.Request中的某个地方,以便在我的处理程序中可以访问它。我该如何做到这一点?这是我所需要的一个小示例:

func test(w http.ResponseWriter, r *http.Request){
    userID := w.UserID // 或者类似这样的方式
}

这个值必须存储在这些变量中的一个,以便我可以在所有的http处理程序中访问它。非常感谢您的时间。

英文:

I need to store the userID somewhere in the w http.ResponseWriter or the req *http.Request, so that in my handlers I can access them.
how can I do this?
this is a small demo for what I need:

func test(w http.ResponseWriter, r *http.Request){
	userID := w.UserID // or something like this
}

again this value MUST be stored in either of these variables so that I can access it in all my http handlers.
Thanks a lot for your time

答案1

得分: 4

你可以将http.ResponseWriter嵌入到自己的结构体中,并添加额外的字段。

type ResponseWriter struct{
    http.ResponseWriter
    UserID int
}

现在使用你的ResponseWriter代替http.ResponseWriter。

希望这可以帮到你。嵌入类型

英文:

You could embed http.ResponseWriter into your own struct and add extra fields

type ResponseWriter struct{
    http.ResponseWriter
    UserID int
}

Now use your ResponseWriter instead of http.ResponseWriter.

I hope this helps. Embeded Types

huangapple
  • 本文由 发表于 2015年8月10日 20:02:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/31919038.html
匿名

发表评论

匿名网友

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

确定