gpt4 book ai didi

go - 无法设置 Cookie。

转载 作者:IT王子 更新时间:2023-10-29 02:28:42 25 4
gpt4 key购买 nike

我定义了两个处理函数,setCookie 和 getCookie。第一个函数 setCookie 通过访问 localhost:8080/set_cookie 来调用,然后发送包含两个 cookie 的 HTTP 响应。另一个函数getCookie是通过访问localhost:8080/get_cookie调用的,获取Cookie对象。我希望 getCookie 函数显示有关两个 cookie 的信息,但在 Web 浏览器上显示一条消息“first_cookie 未成功设置”。

你有解决这个问题的想法吗?

package main

import (
"fmt"
"net/http"
)

func setCookie(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "setCookie called")
c1 := http.Cookie{
Name: "first_cookie",
Value: "Go Web App",
HttpOnly: true,
}
c2 := http.Cookie{
Name: "second_cookie",
Value: "Another service",
HttpOnly: true,
}
http.SetCookie(w, &c1)
http.SetCookie(w, &c2)
}

func getCookie(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "getCookie called")
c1, err := r.Cookie("first_cookie")
if err != nil {
fmt.Fprintln(w, "first_cookie is not set successfully.")
}
ca := r.Cookies()
fmt.Fprintln(w, c1)
fmt.Fprintln(w, ca)
}

func main() {
server := http.Server{
Addr: "127.0.0.1:8080",
}
http.HandleFunc("/set_cookie", setCookie)
http.HandleFunc("/get_cookie", getCookie)
server.ListenAndServe()
}

最佳答案

你的调试语句...

fmt.Fprintln(w, "setCookie called")

... 发生在您的 http.SetCookie 调用之前。

Cookie 是在 header 中设置的,但是通过写入 http.ReponseWriter,您已经触发了设置任何 header 的完成。如果将调试语句移动到 setCookie 的最后一行,它将按预期工作。

您可以通过运行简单地测试它:

curl -v -c "cookie.jar" "http://localhost:8080/set_cookie"

在这样的变化之前和之后。

关于go - 无法设置 Cookie。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50934241/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com