doureng5668 2018-06-19 17:47
浏览 267
已采纳

无法设置Cookie。

I defined two handler functions, setCookie and getCookie. The first function, setCookie, is called by getting access to localhost:8080/set_cookie, and then sends a HTTP response including two cookies. The other function, getCookie, is called by accessing to localhost:8080/get_cookie, and then gets Cookie object. I expect getCookie function to show information about two cookies, but a message, "first_cookie is not set successfully", is shown on a web browser.

Do you have any idea solving this problem?

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条回答 默认 最新

  • dqwh1219 2018-06-19 18:11
    关注

    Your debugging statement...

    fmt.Fprintln(w, "setCookie called")
    

    ... occurs before your http.SetCookie call.

    Cookies are set in headers but by writing to the http.ReponseWriter you've triggered the completion of setting any headers. If you move the debug statement to the last line of setCookie, it will work as expected.

    You can trivially test this by running:

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

    before and after such a change.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘