【问题标题】:Setting up Cookies at browser : Golang在浏览器中设置 Cookie:Golang
【发布时间】:2013-06-09 18:42:19
【问题描述】:

作为 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)
}

但正如预期的那样,这里面临\hello.go:9:15: composite struct literal net/http.Cookie with untagged fields之类的错误

谁能给我建议或给我设置cookie的基本示例(详细)。

在 SO 上几乎没有搜索并发现.. Setting Cookies in Golang (net/http) 但无法正确接收..

谢谢。

【问题讨论】:

  • @stephanos:是的,我知道这一点,但也无法使用,请您详细探讨一下,非常感谢您对此的回复...
  • 尝试使用默认的 cookie 后端 gorillatoolkit.org/pkg/sessions
  • 是的 尝试一下.... 但是如何在我的本地机器(Window 7 64bits)上导入在线包,在 Go SDK 中有 gopath 文件夹.. 下载了三个需要的 .go 文件session.go 但无法在导入中添加本地路径。 gopath 文件夹的路径在环境变量中设置,但仍然出现“解析目录失败”、“无法从如此路径导入”等错误。.. 可以做什么?
  • 如果您的 GOPATH 设置正确,请按照说明使用 go get。无需手动下载文件。
  • 你使用的是什么版本的 go ?输入go version

标签: google-app-engine cookies go


【解决方案1】:

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()

【讨论】:

  • 非常感谢。还将“func main()”替换为“func init()”……然后它就可以工作了。
  • 不客气,不需要将func main() 更改为func init()
  • @Neo 对于 Google App Engine,您需要使用 func init() 而不是 func main()。有点超出问题,但 OP 在 Google App Engine 上,正如您从问题的标记中看到的那样......只是一个细节。
【解决方案2】:

在你链接到它的问题中,基本上说要使用net/http 中的这个函数:

func SetCookie(w ResponseWriter, cookie *Cookie)

所以在你的例子中而不是写

req.AddCookie(&cookie)

你应该写这个

http.SetCookie(w, &cookie)

【讨论】:

  • 谢谢,仍然遇到同样的错误,例如 go-app-builder: Failed parsing input (1 error)composite struct literal net/http.Cookie with untagged fields
  • 我在这里还遗漏了什么吗?关于这些错误的任何猜测或想法
  • 试过完整的测试程序:来自code.google.com/p/go/issues/detail?id=3033链接但是在浏览器上显示“404 page not found”……
猜你喜欢
  • 1970-01-01
  • 2017-05-20
  • 2014-05-07
  • 2018-10-26
  • 2021-09-30
  • 2019-07-25
  • 2023-03-16
  • 2011-06-05
相关资源
最近更新 更多