eeg*_*loo 3 cookies google-app-engine go
作为Golang的新手,尝试在浏览器上设置cookie,有简单的基本代码,但它根本不起作用并进行了一些谷歌搜索并找到了一些stackoverflow ex.但仍然没有采取正确的方式.
创造了一个简单的 hello.go
package main
import "io"
import "net/http"
import "time"
func handler(w http.ResponseWriter, req *http.Request) {
expire := time.Now().AddDate(0, 0, 1)
cookie := http.Cookie{"test", "tcookie", "/", "www.dummy.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("/", handler)
}
Run Code Online (Sandbox Code Playgroud)
但正如预期的那样,我面临着错误 \hello.go:9:15: composite struct literal net/http.Cookie with untagged fields
任何人都可以建议我或给我一些基本的例子(详细说明)来设置cookie.
几乎没有搜索SO并找到.. 在Golang中设置Cookie(net/http)但不能正确地接收它...
谢谢.
cookie := http.Cookie{"test", "tcookie", "/", "www.dummy.com", expire, expire.Format(time.UnixDate), 86400, true, true, "test=tcookie", []string{"test=tcookie"}}
应该是这样的:
cookie := &http.Cookie{Name:"test", Value:"tcookie", Expires:time.Now().Add(356*24*time.Hour), HttpOnly:true}
在这之后
更改
req.AddCookie(&cookie)
至
http.SetCookie(w, cookie)
最后因为你的应用程序在Google App Engine上运行了变化:
func main()
至
func init()
好吧,在您链接到它的问题中,基本上说要从net/http以下位置使用此功能:
func SetCookie(w ResponseWriter, cookie *Cookie)
Run Code Online (Sandbox Code Playgroud)
所以在你的例子中而不是写作
req.AddCookie(&cookie)
Run Code Online (Sandbox Code Playgroud)
你应该写这个
http.SetCookie(w, &cookie)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3539 次 |
| 最近记录: |