package main import ( "fmt" "net/http" "net/url" ) func main() { // ========== 设置cookie『浏览器访问http://localhost:8080/SetCookie』 ========== // http.HandleFunc("/SetCookie", func(writer http.ResponseWriter, request *http.Request) { cookie := http.Cookie{ Name: "name", Value: url.QueryEscape("张三"), // 重要提醒:中文要进行编码处理 } http.SetCookie(writer, &cookie) fmt.Println("设置cookie成功") // 设置cookie成功 }) // ========== 获取cookie『浏览器访问http://localhost:8080/GetCookie』 ========== // http.HandleFunc("/GetCookie", func(writer http.ResponseWriter, request *http.Request) { cookie, err := request.Cookie("name") if err == nil { value, _ := url.QueryUnescape(cookie.Value) // 由于设置cookie时进行了编码,故获取时要解码 fmt.Printf("获取cookie成功,值为:%+v \n", value) // 获取cookie成功,值为:张三 } else { fmt.Printf("获取cookie失败:%+v \n", err.Error()) } }) // ========== 删除cookie『浏览器访问http://localhost:8080/DelCookie』 ========== // http.HandleFunc("/DelCookie", func(writer http.ResponseWriter, request *http.Request) { cookie := http.Cookie{ Name: "name", Value: "", MaxAge: -1, // 重要说明:将MaxAge属性设为负数即可删除cookie } http.SetCookie(writer, &cookie) fmt.Println("删除cookie成功") // 删除cookie成功 }) _ = http.ListenAndServe(":8080", nil) } // ========== 总结 ==========// // 1、调用http.SetCookie()并不是立即往客户端浏览器写cookie,而是随着服务器向客户端返回响应后才写,所以 // 调用http.SetCookie()设置cookie后立即调用request.Cookie()获取cookie是获取不到的。 // 2、调用request.Cookie()获取cookie,若cookie不存在,则err为非nil,错误信息为“http: named cookie not present”。
Copyright © 2024 码农人生. All Rights Reserved