Methods to use Golang to manage HTTP Cookies are: Set Cookie: Use http.Cookie to set its name, value, expiration time, domain, path, security flag and HttpOnly flag, and then use http.SetCookie() to add it to the response header. . Get a Cookie: Use r.Cookie() to get a cookie with a specific name, whose value can then be accessed using its Value field. Deleting the cookie: After retrieving the cookie, setting its Expires field to a time in the past and adding it to the response header will delete the cookie from the client browser.
#How to use Golang to manage HTTP Cookies?
The common way to manage HTTP cookies in Golang is to use the API provided by the net/http package. Here are the steps on how to set, get and delete HTTP cookies:
Set Cookie
package main import ( "fmt" "net/http" "time" ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { // 设置名为 "session_id" 的 cookie,并将它的值设置为 "some-uuid" cookie := &http.Cookie{ Name: "session_id", Value: "some-uuid", } // 设置 cookie 的过期时间 cookie.Expires = time.Now().Add(24 * time.Hour) // 设置 cookie 的域(默认为当前请求的域) cookie.Domain = "example.com" // 设置 cookie 的路径(默认为 "/") cookie.Path = "/" // 设置 cookie 的安全标志(默认为 false) cookie.Secure = true // 设置 cookie 的 HttpOnly 标志(默认为 false) cookie.HttpOnly = true // 将 cookie 添加到响应头上 http.SetCookie(w, cookie) fmt.Fprint(w, "Cookie set successfully") }) http.ListenAndServe(":8080", nil) }
Get Cookie
package main import ( "fmt" "net/http" ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { // 获取名为 "session_id" 的 cookie cookie, err := r.Cookie("session_id") if err != nil { fmt.Fprint(w, "Cookie not found") return } // 打印 cookie 的值 fmt.Fprint(w, "Cookie value:", cookie.Value) }) http.ListenAndServe(":8080", nil) }
Delete Cookie
package main import ( "fmt" "net/http" ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { // 获取名为 "session_id" 的 cookie cookie, err := r.Cookie("session_id") if err != nil { fmt.Fprint(w, "Cookie not found") return } // 设置 cookie 的过期时间为过去,从而删除它 cookie.Expires = time.Now().Add(-1 * time.Second) // 将 cookie 添加到响应头上 http.SetCookie(w, cookie) fmt.Fprint(w, "Cookie deleted successfully") }) http.ListenAndServe(":8080", nil) }
The above is the detailed content of How to manage HTTP cookies using Golang?. For more information, please follow other related articles on the PHP Chinese website!