Golang:检索Gorilla/Sessions Cookie

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

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.

huangapple
  • 本文由 发表于 2015年8月7日 05:06:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/31865799.html
匿名

发表评论

匿名网友

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

确定