I tried the following code. The first time I opened the page, the username
is nil
and the next time, the value turned to be a real name.
func sayHello(w http.ResponseWriter, r *http.Request) {
sess, _ := globalSessions.SessionStart(w, r)
defer sess.SessionRelease(w)
username := sess.Get(r.FormValue("name"))
fmt.Println(username)
sess.Set(r.FormValue("name"), r.FormValue("name"))
}
However, when I am going to implement some complex function, the session does not work.
func loginHandler(w http.ResponseWriter, r *http.Request) {
var (
query url.Values
err error
userInfo daomanage.User
statusInfo StatusInfo
)
cookie, err := r.Cookie("gosessionid")
sess, _ := globalSessions.SessionStart(w, r)
defer sess.SessionRelease(w)
sessionCache := sess.Get(cookie.Value)
log.Println("newcache", sessionCache, cookie.Value)
sess.Set(cookie.Value, cookie.Value)
// symbol xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
if sessionCache != nil {
statusInfo.Status = 200
statusInfo.Info = userInfo.Username
data, _ := json.Marshal(statusInfo)
fmt.Fprintf(w, string(data))
return
}
query, err = url.ParseQuery(r.URL.RawQuery)
if err != nil {
log.Println("Parse Error", err)
return
}
// Get user info
if s, ok := query["username"]; ok {
userInfo, err = daomanage.GetUserInfo("username", s[0])
if err == nil {
if p, ok := query["password"]; ok {
if p[0] == userInfo.Password {
sess.Set(s[0], s[0])
log.Println(sess.Get(s[0]))
tNow := time.Now()
cookie := http.Cookie{Name: "gosessionid", Value: s[0], Expires: tNow.AddDate(1, 0, 0)}
http.SetCookie(w, &cookie)
statusInfo.Status = 200
statusInfo.Info = userInfo.Username
data, _ := json.Marshal(statusInfo)
fmt.Fprintf(w, string(data))
return
}
}
}
}
statusInfo.Status = 400
statusInfo.Info = InfoLoginFailed
data, _ := json.Marshal(statusInfo)
fmt.Fprintf(w, string(data))
return
}
I send the query to the function again and again, but the function sess.Get(cookie.Value)
returns nothing. I even tried to set the session right after the get
function(because in the demo, it works), it still does not work.
When I deleted the code below the symbol, it works again!
Are there any problems? Please help!