在 Golang 中,要移除 Cookie,我们需要设置 Cookie 的 MaxAge 为 -1。
下面是一个基本的示例:
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", handleIndex)
http.HandleFunc("/remove", handleRemoveCookie)
fmt.Println("Server running at http://localhost:8080")
http.ListenAndServe(":8080", nil)
}
func handleIndex(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("mycookie")
if err == nil {
fmt.Fprintln(w, "Cookie Value:", cookie.Value)
} else {
fmt.Fprintln(w, "No Cookie")
}
fmt.Fprintln(w, `Remove Cookie`)
}
func handleRemoveCookie(w http.ResponseWriter, r *http.Request) {
cookie := http.Cookie{Name: "mycookie", MaxAge: -1}
http.SetCookie(w, &cookie)
fmt.Fprintln(w, "Cookie Removed")
}
在上面的示例中,我们定义了两个 HTTP 处理程序:
– handleIndex:它用于显示 Cookie 值,并提供一个链接来移除 Cookie。
– handleRemoveCookie:它用于移除 Cookie,实现方式是创建一个新的名为 mycookie 的 Cookie,将其 MaxAge 设为 -1,然后通过 SetCookie 函数将其发送到客户端。
请注意,在这个示例中,我们没有设置任何 Cookie 值。因此,当您第一次访问页面时,它将显示 “No Cookie”。但是,当您点击 “Remove Cookie” 链接时,它将尝试从请求中获取名为 mycookie 的 Cookie,将其 MaxAge 设置为 -1,然后将其发送回客户端,从而删除该 Cookie。