英文:
How set cookie with go?
问题
我想让我的 Golang 服务器在 HTTP 响应中发送一个 cookie,以便放置在用户的计算机上。
以下是我的代码:
func userLogin(w http.ResponseWriter, r *http.Request) {
cookie := &http.Cookie{
Name: "my-cookie",
Value: "some value",
}
http.SetCookie(w, cookie)
w.WriteHeader(200)
w.Write([]byte("cookie is set"))
return
}
它在头部被标记了。
但是我看不到要创建的 cookie。
英文:
I would like my golang server to send back a cookie in HTTP raiponce that will be placed on the user's computer.
Here is my code
func userLogin(w http.ResponseWriter, r *http.Request) {
cookie := &http.Cookie{
Name: "my-cookie",
Value: "some value",
}
http.SetCookie(w, cookie)
w.WriteHeader(200)
w.Write([]byte("cookie is set))
return
}
it is marked in the header
but I see no cookie to create
答案1
得分: 4
浏览器将cookie路径默认设置为请求路径。
看起来你正在将cookie设置为/<something here>
的请求中,但是你期望在/
的请求中获取cookie。
通过将cookie路径设置为/
来修复。
func userLogin(w http.ResponseWriter, r *http.Request) {
cookie := &http.Cookie{
Name: "my-cookie",
Value: "some value",
Path: "/",
}
http.SetCookie(w, cookie)
w.WriteHeader(200)
w.Write([]byte("cookie is set"))
}
英文:
The browser defaults the cookie path to the request path.
It looks like you are setting the cookie in a request to /<something here>
, but are expecting the cookie in a request to /
.
Fix by setting the cookie path to /
.
func userLogin(w http.ResponseWriter, r *http.Request) {
cookie := &http.Cookie{
Name: "my-cookie",
Value: "some value",
Path: "/",
}
http.SetCookie(w, cookie)
w.WriteHeader(200)
w.Write([]byte("cookie is set))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论