如何使用Go设置cookie?

huangapple go评论97阅读模式
英文:

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

如何使用Go设置cookie?

but I see no cookie to create

如何使用Go设置cookie?

答案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 /&lt;something here&gt;, 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 := &amp;http.Cookie{
            Name:  &quot;my-cookie&quot;,
            Value: &quot;some value&quot;,
            Path: &quot;/&quot;,
        }
        http.SetCookie(w, cookie)
        w.WriteHeader(200)
        w.Write([]byte(&quot;cookie is set))
}

huangapple
  • 本文由 发表于 2021年10月18日 00:34:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/69606445.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定