doujiao1538 2019-04-18 22:06
浏览 97
已采纳

设置Cookie的最大使用期限; 失去最大年龄

So.. I have this unit test:

func TestCookieVoodoo(t *testing.T) {
    req := httptest.NewRequest("GET", "/", nil)

    cookie := http.Cookie{Name: "potato", MaxAge: 1000}

    req.AddCookie(&cookie)

    cookieCopy, _ := req.Cookie("potato")

    println(fmt.Sprintf("Cookie orig: %v", cookie))
    println(fmt.Sprintf("Cookie Copy: %v", *cookieCopy))

    t.Fail()
}

When running it, the output is:

Cookie orig: {potato    0001-01-01 00:00:00 +0000 UTC  1000 false false 0  []}
Cookie copy: {potato    0001-01-01 00:00:00 +0000 UTC  0 false false 0  []}

Why does it loose the max age? (same thing happens when setting other cookie fields) Thanks

  • 写回答

3条回答 默认 最新

  • dtyqflrr775518 2019-04-18 23:22
    关注

    Because the Request.AddCookie only add key and value to the cookie string. the function is:

    func (r *Request) AddCookie(c *Cookie) {
        s := fmt.Sprintf("%s=%s", sanitizeCookieName(c.Name), sanitizeCookieValue(c.Value))
        if c := r.Header.Get("Cookie"); c != "" {
            r.Header.Set("Cookie", c+"; "+s)
        } else {
            r.Header.Set("Cookie", s)
        }
    }
    

    why?

    1. this is the definition of cookie-string in RFC 6265
    2. the Max-Age and other fields of cookie is used by client not server. they are config of client. for example: if the the cookie exprires, client doesn't send key=value to server. So the fields are ignored in request
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题