如何使用 Golang 管理 HTTP cookie?
使用Golang管理HTTPCookie的方法有:设置Cookie:使用http.Cookie设置其名称、值、过期时间、域、路径、安全标志和HttpOnly标志,然后使用http.SetCookie()添加到响应头上。获取Cookie:使用r.Cookie()来获取特定名称的Cookie,然后可以使用它的Value字段访问其值。删除Cookie:获取Cookie后,将其Expires字段设置为过去的时间,并将其添加到响应头上,这会将Cookie从客户端浏览器中删除。
使用 Golang 管理 HTTP Cookie 的方法有:设置 Cookie:使用 http.Cookie 设置其名称、值、过期时间、域、路径、安全标志和 HttpOnly 标志,然后使用 http.SetCookie() 添加到响应头上。获取 Cookie:使用 r.Cookie() 来获取特定名称的 Cookie,然后可以使用它的 Value 字段访问其值。删除 Cookie:获取 Cookie 后,将其 Expires 字段设置为过去的时间,并将其添加到响应头上,这会将 Cookie 从客户端浏览器中删除。

如何使用 Golang 管理 HTTP Cookie?
在 Golang 中管理 HTTP cookie 的常见方法是使用 net/http 包提供的 API。以下是如何设置、获取和删除 HTTP cookie 的步骤:
设置 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)
}获取 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)
}删除 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)
}
火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。
















