我正在使用Go应用程序引擎SDK,并尝试设置/过期Cookie。
设置Cookie没有问题,但是无法使其在浏览器中过期。
该应用程序基于一个negroni
实例:
func init() {
app := negroni.New()
app.UseHandler(Router())
http.Handle("/", app)
}
路由器是一个
mux
实例:func Router() *mux.Router {
r := mux.NewRouter()
subRouter := r.PathPrefix(PATH_PREFIX).Subrouter()
subRouter.HandleFunc("/sign", LoginHandler)
subRouter.HandleFunc("/userinfo", UserInfo)
subRouter.HandleFunc("/logout", Logout)
return r
}
登录处理程序很基础:
func LoginHandler(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)
u := user.Current(ctx)
if u == nil {
url, err := user.LoginURL(ctx, r.URL.String())
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Location", url)
w.WriteHeader(http.StatusFound)
return
}
//COOKIE_ID = "SomeString"
cookie := &http.Cookie{Name: COOKIE_ID, Value: u.ID, Path: "/", MaxAge: 0}
http.SetCookie(w, cookie)
w.Header().Set("Location", "/")
w.WriteHeader(http.StatusFound)
}
将cookie过期:
func Logout(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)
url, err := user.LogoutURL(ctx, "/")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
expiredCookie := &http.Cookie{Name: COOKIE_ID, MaxAge: -10, Expires: time.Now()}
http.SetCookie(w, expiredCookie)
w.Header().Set("Location", url)
w.WriteHeader(http.StatusFound)
}
我尝试了以下方法:
1. 获取旧的cookie,更改MaxAge和Expires 2. 创建一个新的同名cookie来覆盖旧的
完整代码请参见:https://gist.github.com/yageek/78e43c83b56467fc8338 无论如何,在浏览器中cookie仍然存在。我做错了什么?