英文:
Setting cookies with net/http from the server
问题
我正在尝试使用Go的net/http包设置cookie。我有以下代码:
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'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)
}
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.
答案1
得分: 114
我不是Go专家,但我认为你是在请求中设置cookie,对吗?你可能想要在响应中设置它。在net/http中有一个setCookie
函数。这可能会有所帮助:
http://golang.org/pkg/net/http/#SetCookie
func SetCookie(w ResponseWriter, cookie *Cookie)
英文:
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)
答案2
得分: 19
//ShowAllTasksFunc用于处理"/" URL,这是默认的ons
func ShowAllTasksFunc(w http.ResponseWriter, r *http.Request){
if r.Method == "GET" {
context := db.GetTasks("pending") //true when you want non deleted notes
if message != "" {
context.Message = message
}
context.CSRFToken = "abcd"
message = ""
expiration := time.Now().Add(365 * 24 * time.Hour)
cookie := http.Cookie{Name: "csrftoken",Value:"abcd",Expires:expiration}
http.SetCookie(w, &cookie)
homeTemplate.Execute(w, context)
} else {
message = "Method not allowed"
http.Redirect(w, r, "/", http.StatusFound)
}
}
Requests
和ResponseWriter
之间有一个基本的区别,请求是浏览器发送的内容,例如:
Host: 127.0.0.1:8081
User-Agent: ...
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
DNT: 1
Referer: http://127.0.0.1:8081/
Cookie: csrftoken=abcd
Connection: keep-alive
而响应是处理程序发送的内容,类似于:
Content-Type: text/html; charset=utf-8
Date: Tue, 12 Jan 2016 16:43:53 GMT
Set-Cookie: csrftoken=abcd; Expires=Wed, 11 Jan 2017 16:43:53 GMT
Transfer-Encoding: chunked
<html>...</html>
当浏览器发出请求时,它将包含该域的cookie,因为cookie是按域存储的,无法从跨域访问,如果将cookie设置为HTTP only,则只能从通过HTTP设置它的网站访问,而不是通过JS。
因此,当从cookie获取信息时,可以使用r.Cookie方法,如下所示:
cookie, _ := r.Cookie("csrftoken")
if formToken == cookie.Value {
https://github.com/thewhitetulip/Tasks/blob/master/views/addViews.go#L72-L75
但是,当要设置cookie时,必须在响应写入器方法中执行,请求是只读对象,我们对其进行响应,将其视为从某人那里收到的短信,那是一个请求,您只能收到它,您输入的是响应,因此您可以在以下位置输入cookie
更多详细信息:https://thewhitetulip.gitbooks.io/webapp-with-golang-anti-textbook/content/content/2.4workingwithform.html
英文:
//ShowAllTasksFunc is used to handle the "/" URL which is the default ons
func ShowAllTasksFunc(w http.ResponseWriter, r *http.Request){
if r.Method == "GET" {
context := db.GetTasks("pending") //true when you want non deleted notes
if message != "" {
context.Message = message
}
context.CSRFToken = "abcd"
message = ""
expiration := time.Now().Add(365 * 24 * time.Hour)
cookie := http.Cookie{Name: "csrftoken",Value:"abcd",Expires:expiration}
http.SetCookie(w, &cookie)
homeTemplate.Execute(w, context)
} else {
message = "Method not allowed"
http.Redirect(w, r, "/", http.StatusFound)
}
}
There is a basic difference between Requests
and ResponseWriter
, a Request is what a browser will send like
Host: 127.0.0.1:8081
User-Agent: ...
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
DNT: 1
Referer: http://127.0.0.1:8081/
Cookie: csrftoken=abcd
Connection: keep-alive
and a response is what the handler will send, something like :
Content-Type: text/html; charset=utf-8
Date: Tue, 12 Jan 2016 16:43:53 GMT
Set-Cookie: csrftoken=abcd; Expires=Wed, 11 Jan 2017 16:43:53 GMT
Transfer-Encoding: chunked
<html>...</html>
When the browser will make a request, it'll include the cookie for that domain, since cookies are stored domain wise and can't be accessed from cross domains, if you set a cookie as HTTP only then it can only be accessed from the website which set it via HTTP and not via JS.
So when getting information from cookies you can do that from the r.Cookie method, like this
cookie, _ := r.Cookie("csrftoken")
if formToken == cookie.Value {
https://github.com/thewhitetulip/Tasks/blob/master/views/addViews.go#L72-L75
But when you are going to set a cookie, you have to do it in the response writer method, the request is a read only object which we respond to, think of it as a text message you get from someone, that is a request, you can only get it, what you type is a response, so you can type in a cookie at
for more details: https://thewhitetulip.gitbooks.io/webapp-with-golang-anti-textbook/content/content/2.4workingwithform.html
答案3
得分: 14
cookie1 := &http.Cookie{Name: "sample", Value: "sample", HttpOnly: false}
http.SetCookie(w, cookie1)
英文:
This Below code helps u
cookie1 := &http.Cookie{Name: "sample", Value: "sample", HttpOnly: false}
http.SetCookie(w, cookie1)
答案4
得分: 9
以下展示了我们在产品中如何使用cookie:
func handleFoo(w http.ResponseWriter, r *http.Request) {
// cookie将在1年后过期
expires := time.Now().AddDate(1, 0, 0)
ck := http.Cookie{
Name: "JSESSION_ID",
Domain: "foo.com",
Path: "/",
Expires: expires,
}
// cookie的值
ck.Value = "这个很棒的cookie的值"
// 将cookie写入响应
http.SetCookie(w, &ck)
// ...
}
英文:
Below shows how we use cookie in our product:
func handleFoo(w http.ResponseWriter, r *http.Request) {
// cookie will get expired after 1 year
expires := time.Now().AddDate(1, 0, 0)
ck := http.Cookie{
Name: "JSESSION_ID",
Domain: "foo.com",
Path: "/",
Expires: expires,
}
// value of cookie
ck.Value = "value of this awesome cookie"
// write the cookie to response
http.SetCookie(w, &ck)
// ...
}
答案5
得分: 5
在Safari中,直到我添加了Path和MaxAge,它才对我起作用。对我来说,安全和常规的cookie都起作用。
分享一下,希望能帮助那些像我一样被困了两天以上的人
expire := time.Now().Add(20 * time.Minute) // 20分钟后过期
cookie := http.Cookie{Name: "username", Value: "nonsecureuser", Path: "/", Expires: expire, MaxAge: 86400}
http.SetCookie(w, &cookie)
cookie = http.Cookie{Name: "secureusername", Value: "secureuser", Path: "/", Expires: expire, MaxAge: 86400, HttpOnly: true, Secure: true}
http.SetCookie(w, &cookie)
英文:
It was not working for me in Safari until I added the Path and MaxAge. Both secure and regular cookies worked for me
Sharing so that it helps someone who is stuck like me for more than 2 days
expire := time.Now().Add(20 * time.Minute) // Expires in 20 minutes
cookie := http.Cookie{Name: "username", Value: "nonsecureuser", Path: "/", Expires: expire, MaxAge: 86400}
http.SetCookie(w, &cookie)
cookie = http.Cookie{Name: "secureusername", Value: "secureuser", Path: "/", Expires: expire, MaxAge: 86400, HttpOnly: true, Secure: true}
http.SetCookie(w, &cookie)
答案6
得分: 4
首先,您需要创建Cookie,然后使用http包的SetCookie()函数来设置Cookie。
expire := time.Now().Add(10 * time.Minute)
cookie := http.Cookie{Name: "User", Value: "John", Path: "/", Expires: expire, MaxAge: 90000}
http.SetCookie(w, &cookie)
英文:
First, you need to create Cookie and then using http package's SetCookie() function you can set the cookie.
expire := time.Now().Add(10 * time.Minute)
cookie := http.Cookie{Name: "User", Value: "John", Path: "/", Expires: expire, MaxAge: 90000}
http.SetCookie(w, &cookie)
答案7
得分: -2
你可以使用gorilla包来处理cookie,或者我可以说是安全的cookie:http://www.gorillatoolkit.org/pkg/securecookie
英文:
You can use gorilla package for handling cookies or i would say secure cookies: http://www.gorillatoolkit.org/pkg/securecookie
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论