我目前正在使用Go App Engine 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) }
我尝试了一切:
获取旧cookie,更改MaxAge和Expires
创建一个具有相同名称的新cookie以覆盖
完整代码:https://gist.github.com/yageek/78e43c83b56467fc8338
在任何情况下,cookie仍然保留在导航器中.我做错了什么?
浏览器存储多个路径的cookie.在cookie标头上设置path属性以匹配用于创建cookie的路径属性.
将最大年龄设置为负值以清除cookie.如果等于零,则不在标题上设置最大年龄属性.
某些浏览器不了解最大年龄属性.为了这些浏览器的利益,将过期时间设置为过去的时间.
expiredCookie := &http.Cookie{Path: "/", Name: COOKIE_ID, MaxAge: -1, Expires: time.Now().Add(-100 * time.Hour)}