回答

收藏

使用 net/http 设置 cookie

技术问答 技术问答 602 人阅读 | 0 人回复 | 2023-09-12

我试着用 Go 的 net/http 包设置 cookie。我有:
% X( f5 Y% h$ ^) n* f. g
    package mainimport "io"import "net/http"import "time"func indexHandler(w http.ResponseWriter,req *http.Request)    expire := time.Now().AddDate    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)}9 n: R' d7 \9 j% `$ d' h
我尝试用 ‘cookies’ 搜索 ‘Golang’,但没有得到任何好的结果。如果有人能指出我的正确方向,我将非常感激。
. d, T2 f8 u1 K" Z5 E* X                                                                . [3 h# k( u0 ^; E4 C! a
    解决方案:                                                               
8 G1 P5 M( U1 R                                                                我不是go专家,但我认为你上设置了 cookie,不是吗?您可能希望在响应中设置它。setCookienet/http 中有一个函数。这可能会有所帮助:http : //golang.org/pkg/net/http/#SetCookie
0 b% ]" l% J6 {: o
    func SetCookie(w ResponseWriter,cookie *Cookie)
    , f7 }( w) Y: ]% l; Q! \  p# z. \# c
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则