3
我目前正在使用Go App Engine SDK,並試圖設置/過期Cookie。Golang - 無法過期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,改變最大生存週期和過期
- 創建具有相同名稱的一個新的cookie覆蓋
全碼:https://gist.github.com/yageek/78e43c83b56467fc8338
在任何情況下,Cookie仍保留在導航器中。我做錯了什麼?