我正在使用 Go 制作一个简单的 Web 应用程序,使用 gorilla 进行会话和路由,使用 Mustache 进行模板。我在登录时遇到问题,我相信是 IE 接受 cookie 的问题。该问题仅出现在 Internet Explorer 中,但在 Chrome 中登录可以正常工作。这是我的代码:
func main() {
r := mux.NewRouter()
r.HandleFunc("/performance", Index)
r.HandleFunc("/performance/login", Login)
log.Fatal(http.ListenAndServe(":5901", r))
}
func Index(w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, "performance")
if session.Values["username"] == nil {
http.Redirect(w, r, "/performance/login", http.StatusSeeOther)
}
dict := session.Values
fmt.Fprintf(w, mustache.RenderFileInLayout("templates/index.html", "templates/basepage.html", dict))
}
func Login(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
results := 0
r.ParseForm()
u := r.FormValue("username")
pass := r.FormValue("password")
p := PassEncrypt(pass)
q := map[string]string{}
rows, err := db.Query("SELECT username, name, title FROM user WHERE (username=$1) AND (password=$2)", u, p)
if err != nil {
log.Fatal(err)
}
for rows.Next() {
var username string
var name string
var title string
if err := rows.Scan(&username, &name, &title); err != nil {
log.Fatal(err)
}
q["username"] = username
q["name"] = name
q["title"] = title
results++
}
if results > 0 {
session, _ := store.Get(r, "performance")
session.Options = &sessions.Options{
MaxAge: 900,
}
session.Values["username"] = q["username"]
session.Values["name"] = q["name"]
session.Values["title"] = q["title"]
session.Save(r, w)
http.Redirect(w, r, "/performance", http.StatusSeeOther)
} else {
http.Redirect(w, r, "/performance/login", http.StatusSeeOther)
}
} else {
fmt.Fprintf(w, mustache.RenderFileInLayout("templates/login.html", "templates/basepage.html", nil))
}
}
使用 IE 登录时,用户会被重定向回登录页面,因为会话值“用户名”为零,而在 Chrome 中,用户名已正确定义并提供索引页面。由于某种原因 IE 不接受 cookie,但我更改了 IE 中的所有设置以允许来自任何站点的 cookie。我是否需要更改 cookie 选项之一或向 cookie 添加除“MaxAge”之外的其他内容,以便 IE 接受它?提前致谢。