How to delete cookies

I wrote a web application that sets a cookie and deletes it. To clarify the scenario, I mean the following piece of code.

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 go to / cookie, it will be set as a cookie. Then when I call / delete it should change the name, value and elapsed time from the cookie. The elapsed time changes, but the name and value do not.

enter image description here

What I need is to delete the cookie from the browser to log out of the authentication system when the user clicks the logout button to delete the cookie.
I also open this link and follow the guidelines, but it doesn't work as expected.

+3


source to share


2 answers


Cookies are entered by name, so when you "change" the name, you actually "create" another cookie that has expired already.



Keep the name the same and it should work, but remember to take some time in one day to read about cookies and how they work.

+3


source


To delete a cookie named "storage", send a set-cookie with the same cookie name.

deleteCookieHandler () should be as follows



c := &http.Cookie{
    Name:     "storage",
    Value:    "",
    Path:     "/",
    Expires: time.Unix(0, 0),

    HttpOnly: true,
}

http.SetCookie(rw, c)

      

+3


source







All Articles