如何删除cookie [英] How to delete cookie

查看:421
本文介绍了如何删除cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个Web应用程序,设置一个cookie并删除它。为了澄清场景我的意思是看下面的代码片段。

I wrote a web application that set a cookie and delete it. To clarify to scenario what I mean look at the following code snippet.

package main

import (
    "fmt"
    "github.com/gorilla/mux"
    "net/http"
    "time"
)

func rootHandler(rw http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(rw, "Hello Foo")

}

func setCookieHandler(rw http.ResponseWriter, r *http.Request) {
    c := &http.Cookie{
        Name:     "storage",
        Value:    "value",
        Path:     "/",
        MaxAge:   0,
        HttpOnly: true,
    }

    http.SetCookie(rw, c)
}

func deleteCookieHandler(rw http.ResponseWriter, r *http.Request) {

    c, err := r.Cookie("storage")
    if err != nil {
        panic(err.Error())
    }
    c.Name = "Deleted"
    c.Value = "Unuse"
    c.Expires = time.Unix(1414414788, 1414414788000)
}

func readCookieHandler(rw http.ResponseWriter, r *http.Request) {

    c, err := r.Cookie("storage")
    if err != nil {
        panic(err.Error())
    }
    fmt.Println(c.Expires)
}

func evaluateCookieHandler(rw http.ResponseWriter, r *http.Request) {

    c, err := r.Cookie("storage")
    if err != nil {
        panic(err.Error())
    }

    if time.Now().After(c.Expires) {
        fmt.Println("Cookie is expired.")
    }
}

func main() {
    mux := mux.NewRouter()
    mux.HandleFunc("/", rootHandler)
    mux.HandleFunc("/cookie", setCookieHandler)
    mux.HandleFunc("/delete", deleteCookieHandler)
    mux.HandleFunc("/read", readCookieHandler)
    mux.HandleFunc("/eval", evaluateCookieHandler)

    http.ListenAndServe(":3000", mux)
}

正如你所看到的,当我访问/ cookie位置,它会按预期设置一个cookie。然后当我调用/删除,它应该更改名称,值和过期时间从cookie。已过期的时间已更改,但名称和值不会更改。

As you can see, when I visit /cookie location, it will be set a cookie as expected. Then when I call /delete, it should change the name, value and expired time from cookie. The expired time is changed, but name and value not.

>

我想要的是,当用户点击退出按钮删除cookie时,从浏览器中删除cookie以退出认证系统。

我也发现此链接,并按照建议操作,但无法按预期工作。

What do I want is, to delete the cookie from browser for sign out in a authentication system, when user click sign out button to delete cookie.
I also discover this link and follow the advice, but does not work as expected.

推荐答案

Cookie是以名称命名的,所以当您更改名称时,实际上创建

Cookies are keyed by name, so when you "change" the name, you actually "create" a different cookie, already expired.

保持相同的名称,它应该工作,但不要忘了花一些时间阅读有关cookie及其工作原理。

Keep the name the same and it should work, but don't forget to take some time one day to read about cookies and how they work.

这篇关于如何删除cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆