首页 > 后端开发 > Golang > 如何使用Go的net/http包正确设置cookies?

如何使用Go的net/http包正确设置cookies?

Susan Sarandon
发布: 2024-12-21 05:50:12
原创
346 人浏览过

How to Correctly Set Cookies Using Go's net/http Package?

从服务器使用 Go 的 net/http 设置 Cookie

使用 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)
}
登录后复制

说明

在此示例:

  • http.SetCookie(w, cookie) 用于将 cookie 添加到响应中。
  • cookie 配置了各种属性,例如名称、值、路径、域名、过期时间和安全设置。
  • fmt.Fprint(w, "Hello world!") 将响应发送到客户端,包括设置饼干。

以上是如何使用Go的net/http包正确设置cookies?的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板