无法设置Cookie。

时间:2018-06-19 17:47:56

标签: go cookies

我定义了两个处理程序函数setCookie和getCookie。 通过访问localhost:8080 / set_cookie来调用第一个函数setCookie,然后发送包含两个cookie的HTTP响应。 通过访问localhost:8080 / get_cookie调用另一个函数getCookie,然后获取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()
}

1 个答案:

答案 0 :(得分:4)

您的调试语句...

fmt.Fprintln(w, "setCookie called")

...发生在您的http.SetCookie通话之前。

Cookie设置在标题中,但是通过写入http.ReponseWriter,您触发了所有标题设置的完成。如果将调试语句移到setCookie的最后一行,它将按预期运行。

您可以通过运行以下内容对其进行简单测试:

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

更改前后。

相关问题