小编典典

使用 net/http 设置 cookie

go

我正在尝试使用 Go 的 net/http 包设置 cookie。我有:

package main

import "io"
import "net/http"
import "time"

func indexHandler(w http.ResponseWriter, req *http.Request) {
    expire := time.Now().AddDate(0, 0, 1)
    cookie := http.Cookie{"test", "tcookie", "/", "www.domain.com", expire, expire.Format(time.UnixDate), 86400, true, true, "test=tcookie", []string{"test=tcookie"}}
    req.AddCookie(&cookie)
    io.WriteString(w, "Hello world!")
}

func main() {
    http.HandleFunc("/", indexHandler)
    http.ListenAndServe(":80", nil)
}

我尝试用 ‘cookies’ 搜索 ‘Golang’,但没有得到任何好的结果。如果有人能指出我正确的方向,将不胜感激。


阅读 206

收藏
2021-12-20

共1个答案

小编典典

我不是go专家,但我认为您是在请求上设置 cookie,不是吗?您可能希望在响应中设置它。setCookienet/http 中有一个函数。这可能会有所帮助:http : //golang.org/pkg/net/http/#SetCookie

func SetCookie(w ResponseWriter, cookie *Cookie)
2021-12-20