dongqiangou5724 2014-12-27 20:13
浏览 143
已采纳

如何删除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)
}

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.

enter image description here

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.

  • 写回答

2条回答 默认 最新

  • drbl91357 2014-12-27 20:33
    关注

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

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元