<p>Are there any issues that can present themselves by doing the following to store user info for the duration of a request? If I have multiple users accessing the service at once, is there any risk of the UserController.User getting mixed up with another user? It seems to be working but I haven't tested it under heavy load.</p>
<pre><code>package main
type UserController struct {
Udb *UrlDB
User models.User
}
func (uc *UserController) SomeHTTPHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
// Do something with current user.
}
func (uc *UserController) AuthMiddleware(fn func(http.ResponseWriter, *http.Request, httprouter.Params), to string) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
theJWT, err = jwt.Get(r) // Get JWT from cookie
if err != nil {
// Bad or no JWT, clear cookies, redirect appropriately
return
}
uc.User.Email = theJWT["user"]
uc.User.Load() // Loads the rest of the user info from the database and stores it in User model
fn(w, r, ps)
}
}
func main() {
uc := &UserController{}
gdb := &controllers.UrlDB{}
gdb.Open()
defer gdb.Db.Close()
uc.Udb = gdb
router := httprouter.New()
router.GET("/", uc.AuthMiddleware(uc.SomeHTTPHandler, "/login/"))
log.Fatal(http.ListenAndServe(":8080", router))
}
</code></pre>
<hr/>
<pre><code>package models
type User struct {
Email string `json:"email"`
Name string `json:"name"`
Id string `json:"id"`
}
</code></pre>
<hr/>
<pre><code>package controllers
type UrlDB struct {
Db *sql.DB
}
</code></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传