亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Golang Cookie未刪除

Golang Cookie未刪除

Go
Helenr 2021-03-30 16:18:05
在嘗試測試以下代碼時://SetSingleSignOn Sets the cookie to allow for single sign cross applications.func SetSingleSignOn(w http.ResponseWriter, token string) {    http.SetCookie(w, &http.Cookie{        Name:     ssoCookie,        Value:    token,        Path:     "/",        HttpOnly: false,        Secure:   false,        Domain:   "localhost",        Expires:  time.Now().AddDate(0, 0, 7),        MaxAge:   0,    })}//DestroySingleSignOn Gets rid of single sign on, in case a user logs out of the application.func DestroySingleSignOn(r *http.Request, w http.ResponseWriter) {    cookie, err := r.Cookie(ssoCookie)    if err != nil || cookie.Value == "" {        return    }    cookie = &http.Cookie{        Name:     ssoCookie,        Path:     "/",        HttpOnly: false,        Secure:   false,        Domain:   "localhost",        Expires:  time.Now(),        MaxAge:   -1}    http.SetCookie(w, cookie)}我遇到了明顯的錯誤失敗。我所有的SetSingleSignOn通過測試,但健全性測試DestroySingleSignOn失敗。好像http.SetCookie(w, cookie)根本沒有調用過!更離奇的是,當我取消對函數的直接調用時http.SetCookie(w, &http.Cookie{    Name:     ssoCookie,    Path:     "/",    HttpOnly: false,    Secure:   false,    Domain:   "localhost",    Expires:  time.Now(),    MaxAge:   -1}它似乎可以正常工作(最后一個cookie處于非活動狀態),但是現在其中有兩個cookie res.Cookies()!是什么原因造成的?
查看完整描述

1 回答

?
一只萌萌小番薯

TA貢獻1795條經驗 獲得超7個贊

在您的DestorySingleSignOn函數中,您將從以下代碼塊開始:


cookie, err := r.Cookie(ssoCookie)

if err != nil || cookie.Value == "" {

    return

}

請注意,您正在檢查請求上的cookie ,但僅在response上設置了cookie 。您將需要發出請求以獲取初始cookie集,然后使用該cookie發出第二個請求才能使它起作用。


t.Run("SignedOnFirst", func(t *testing.T) {


    req := httptest.NewRequest("POST",

        "localhost:42100",

        nil)

    w := httptest.NewRecorder()


    SetSingleSignOn(w, "12446rewa12314")


    // get the initial cookie

    res := w.Result()

    cookie := res.Cookies()[0]


    // issue a second request with the cookie

    req = httptest.NewRequest("POST",

        "localhost:42100",

        nil)

    req.AddCookie(cookie)

    w = httptest.NewRecorder()


    // assert.NotPanics(t, func() { DestroySingleSignOn(req, w) })

    DestroySingleSignOn(req, w)


    // get the new cookie

    res = w.Result()

    fmt.Println(res.Cookies())


    assert.Equal(t, 1, len(res.Cookies()))

    cookie = *res.Cookies()[0]

    // cookie should be named ssoCookie

    assert.Equal(t,

        ssoCookie,

        cookie.Name)


    // cookie should have already expired

    assert.True(t,

        time.Now().After(cookie.Expires))


})


查看完整回答
反對 回復 2021-04-19
  • 1 回答
  • 0 關注
  • 292 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號