使用 Go 的 net/http 包设置 cookie 可能是一项简单的任务。然而,一个常见的陷阱是尝试在请求对象上设置 cookie,而不是响应。
以下是如何使用 net/http 正确设置 cookie:
package main import ( "fmt" "net/http" "time" ) func indexHandler(w http.ResponseWriter, req *http.Request) { expire := time.Now().AddDate(0, 0, 1) cookie := &http.Cookie{ Name: "test", Value: "tcookie", Path: "/", Domain: "www.domain.com", Expires: expire, RawExpires: expire.Format(time.UnixDate), MaxAge: 86400, Secure: true, HttpOnly: true, SameSite: http.SameSiteStrictMode, Raw: "test=tcookie", Unparsed: []string{"test=tcookie"}, } http.SetCookie(w, cookie) // Set the cookie on the response fmt.Fprint(w, "Hello world!") } func main() { http.HandleFunc("/", indexHandler) http.ListenAndServe(":80", nil) }
在此示例:
以上是如何使用Go的net/http包正确设置cookies?的详细内容。更多信息请关注PHP中文网其他相关文章!