douxun1934 2017-12-04 04:36
浏览 32
已采纳

设置未检测到Cookie

I'm running into a problem trying to retrieve a cookie if it is set and if not I want to update it then retrieve it.

To start I have a function that sets a cookie:

func IndexHandler(w http.ResponseWriter, r *http.Request) {
    ...
    ck := http.Cookie{
        Name: "id",
        Value: 5,
        MaxAge: 60,
    }
}

Then in another function I check to see if that cookie exists and if it (throws an error) then I recreate it

func CheckUpdateCookie(w http.ResponseWriter, r *http.Request) {
    val, err := r.Cookie("id")
    if err != nil {
        ck := http.Cookie{
            Name: "id",
            Value: 5,
            MaxAge: 60,
        }

        http.SetCookie(w, &ck)
        CheckUpdateCookie(w, r)
    }
}

This leads to it running into an infinite loop and not recognizing that the cookie has been set again, if I print the err I get http: named cookie not present even though I have set the cookie in the body of the function.

  • 写回答

1条回答 默认 最新

  • dprc88435 2017-12-04 04:43
    关注

    The call to r.Cookie("id") reads a "Cookie" header in the request.

    The call to http.SetCookie(w, &ck) adds a "Set-Cookie" header in the response. The call does not modify the request.

    Instead of calling the function recursively to get the cookie (which does not work for the reasons stated above), just use the cookie you have on hand:

    func CheckUpdateCookie(w http.ResponseWriter, r *http.Request) {
        val, err := r.Cookie("id")
        if err != nil {
            val := &http.Cookie{
                Name: "id",
                Value: 5,
                MaxAge: 60,
            }
            http.SetCookie(w, val)
        }
        // val is now set to the cookie.
    }
    

    It is typical to set the path to "/" so that the cookie is available on all paths:

            val := &http.Cookie{
                Name: "id",
                Value: 5,
                MaxAge: 60,
                Path: "/",
            }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 vmware exsi重置后的密码
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面