使用net / http设置cookie
问题描述:
我正在尝试使用Go的net / http软件包设置Cookie。我有:
I'm trying to set cookies with Go's net/http package. I have:
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)
}
我尝试将 Golang与 cookies进行谷歌搜索,但没有得到任何良好的结果。如果有人能向我指出正确的方向,将不胜感激。
I tried googling 'Golang' with 'cookies', but didn't get any good results. If anyone can point me in the right direction it would be greatly appreciated.
答
我不是Go专家,但我认为您是在请求中设置Cookie,不是吗?您可能要在响应上进行设置。 net / http中有一个 setCookie
函数。这可能会有所帮助:
http://golang.org/pkg/net/http/ #SetCookie
I am not a Go expert, but I think you are setting the cookie on the request, aren't you? You might want to set it on the response. There is a setCookie
function in net/http. This might help:
http://golang.org/pkg/net/http/#SetCookie
func SetCookie(w ResponseWriter, cookie *Cookie)