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 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换