英文:
Golang: Retrieving Gorilla/Sessions Cookie
问题
我正在尝试通过s.Save(r, w)来查找保存到客户端浏览器的cookie值。这样我就可以在调用renderTemplate()之前将cookie值存储到数据库中。是否可以使用gorilla/sessions api来实现这一点?
func login(w http.ResponseWriter, r *http.Request, db *sql.DB, store *sessions.CookieStore, t *template.Template){
if r.Method == "POST" {
r.ParseForm()
username, password, remember := r.FormValue("user[name]"), r.FormValue("user
"), r.FormValue("remember_me")
User, err := users.Login(db, username, password, remember, r.RemoteAddr)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
s, _ := store.Get(r, "rp-session") //返回一个新的session
s.Save(r, w)
//fmt.Println(s.Values)
renderTemplate(w, "user_nav_info", t, User)
}
}
以上是要翻译的内容。
英文:
I'm trying to find out the cookie value that is being saved to the clients browser via s.Save(r, w). That way I can store the cookie value in a database before calling renderTemplate(). Is there a way to accomplish this using the gorilla/sessions api?
func login(w http.ResponseWriter, r *http.Request, db *sql.DB, store *sessions.CookieStore, t *template.Template){
if r.Method == "POST" {
r.ParseForm()
username, password, remember := r.FormValue("user[name]"), r.FormValue("user
"), r.FormValue("remember_me")
User, err := users.Login(db, username, password, remember, r.RemoteAddr)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
s, _ := store.Get(r, "rp-session") //returns a new session
s.Save(r, w)
//fmt.Println(s.Values)
renderTemplate(w, "user_nav_info", t, User)
}
}
答案1
得分: 0
这是gorilla的sessions API如何保存会话的方式-https://github.com/gorilla/sessions/blob/master/store.go#L104-L109
因此,您可以将以下代码包含在其中,以获取在客户端机器上设置的确切cookie值。
encoded, err := securecookie.EncodeMulti(s.Name(), s.Values, store.Codecs...)
if err != nil {
return err
}
cookieVal := NewCookie(s.Name(), encoded, s.Options)
fmt.Println(cookieVal) // 发送给客户端的cookie值
尽管如此,我不建议您以这种方式保存cookie。gorilla的sessions API应该为您完成这项工作。
英文:
This is how gorilla's sessions api saves the session - https://github.com/gorilla/sessions/blob/master/store.go#L104-L109
So, you can essentially include the below code to get the exact cookie value being set in client's machine.
encoded, err := securecookie.EncodeMulti(s.Name(), s.Values, store.Codecs...)
if err != nil {
return err
}
cookieVal := NewCookie(s.Name(), encoded, s.Options)
fmt.Println(cookieVal) // cookie value that is sent to client
Although, I'd not suggest you to save the cookie that way. gorilla's sessions api is supposed to the job for you.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论