回答

收藏

使用 net/http 设置 cookie

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

我试着用 Go 的 net/http 包设置 cookie。我有:
5 Q! E2 Z! q' B8 q7 y3 x8 _7 l
    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)}
    & E7 {5 j8 c& J3 a% J2 i: u% R& A! |
我尝试用 ‘cookies’ 搜索 ‘Golang’,但没有得到任何好的结果。如果有人能指出我的正确方向,我将非常感激。
$ H2 i* x& T$ |) W, Z+ E( ]                                                               
/ v4 \5 N$ F; t/ T+ @4 m    解决方案:                                                                ! ?1 v& A$ k& N0 [$ h
                                                                我不是go专家,但我认为你上设置了 cookie,不是吗?您可能希望在响应中设置它。setCookienet/http 中有一个函数。这可能会有所帮助:http : //golang.org/pkg/net/http/#SetCookie! v6 V& T* I7 s4 A5 c, h& m; Y
    func SetCookie(w ResponseWriter,cookie *Cookie). G( v- i( v5 R* B+ k. e
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则