登录
首页 >  Golang >  Go问答

为何 gin 的 SetCookie 方法在添加新 cookie 时不修改旧 cookie?

来源:stackoverflow

时间:2024-03-25 23:09:43 212浏览 收藏

在 Gin 中,`SetCookie` 方法不会修改现有的 cookie,而是添加一个新的 cookie。当使用 `SetCookie` 方法时,它会将新的 cookie 添加到响应头中,而不会覆盖或修改现有的 cookie。要解决这个问题,可以考虑使用 `AddCookie` 方法,它允许添加一个新的 cookie 而不覆盖现有的 cookie。

问题内容

我正在尝试测试注销处理程序,其中有一个 ctx.setcookie 方法:

func (a *authcontroller) logout(ctx *gin.context) {
    refreshtoken, err := ctx.cookie("refresh_token")
    ...
    ctx.setcookie("access_token", "", -1, "/", "localhost", false, true)
    ctx.setcookie("refresh_token", "", -1, "/", "localhost", false, true)
    ctx.setcookie("logged_in", "", -1, "/", "localhost", false, true)

    ctx.json(http.statusok, gin.h{"status": "success"})

}

测试函数内的代码:

recorder := httptest.newrecorder()
ctx, _ := gin.createtestcontext(recorder)
ctx.setcookie("logged_in", "truee", 60*60, "/", "localhost", false, false)
req, _ := http.newrequest("get", "/logout", nil)
http.setcookie(recorder, &http.cookie{name: "refresh_token", value: "encodedrefreshtoken", maxage: 60 * 60, path: "/", domain: "localhost", secure: false, httponly: true}})
http.setcookie(recorder, &http.cookie{name: "access_token", value: "encodedaccesstoken", maxage: 60 * 60, path: "/", domain: "localhost", secure: false, httponly: true})
req.header = http.header{"cookie": recorder.result().header["set-cookie"]}
ctx.request = req
test.mock()
authcontroller.logout(ctx)

通话结束后,我尝试检查 cookie 是否已被删除:

coockies := recorder.Result().Cookies()
for _, c := range coockies {
    if c.Name == "access_token" {
        assert.Equal(t, "", c.Value)
    }
    ...
}

而且我面临这样的问题:setcookie 不会更改 cookies,而是添加新的 cookies。也就是说,调用这个方法后,我就有了两对带有access token等的cookie

结果,测试没有通过。我不明白我做错了什么,可以以某种方式解决吗?或者应该是这样吗?


正确答案


使用addcookierecorder设置cookie。

我认为您应该像这样测试 logout 处理程序:

package ${your_package}

import (
    "encoding/json"
    "net/http"
    "net/http/httptest"
    "testing"

    "github.com/gin-gonic/gin"
    "github.com/stretchr/testify/assert"
)

func logout(ctx *gin.context) {
    // refreshtoken, err := ctx.cookie("refresh_token")
    ctx.setcookie("access_token", "", -1, "/", "localhost", false, true)
    ctx.setcookie("refresh_token", "", -1, "/", "localhost", false, true)
    ctx.setcookie("logged_in", "", -1, "/", "localhost", false, true)

    ctx.json(http.statusok, gin.h{"status": "success"})
}

func setuprouter() *gin.engine {
    r := gin.default()
    r.get("/logout", logout)
    return r
}

func testlogout(t *testing.t) {
    w := httptest.newrecorder()
    r := setuprouter()
    req, err := http.newrequest("get", "/logout", nil)
    assert.nil(t, err)
    req.addcookie(&http.cookie{name: "refresh_token", value: "encodedrefreshtoken", maxage: 60 * 60, path: "/", domain: "localhost", secure: false, httponly: true})
    req.addcookie(&http.cookie{name: "access_token", value: "encodedaccesstoken", maxage: 60 * 60, path: "/", domain: "localhost", secure: false, httponly: true})
    r.servehttp(w, req)

    for _, v := range w.result().cookies() {
        if v.name == "access_token" {
            assert.equal(t, "", v.value)
        }
    }
    assert.equal(t, http.statusok, w.code)
    respbody := &gin.h{}
    err = json.unmarshal(w.body.bytes(), respbody)
    assert.nil(t, err)
    assert.equal(t, gin.h{"status": "success"}, *respbody)
}
=== RUN   TestLogout
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.

[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
 - using env:   export GIN_MODE=release
 - using code:  gin.SetMode(gin.ReleaseMode)

[GIN-debug] GET    /logout                   --> app.Logout (3 handlers)
[GIN] 2022/09/19 - 10:46:00 | 200 |          81µs |                 | GET      "/logout"
--- PASS: TestLogout (0.00s)
PASS

参考号:https://gin-gonic.com/docs/testing/

好了,本文到此结束,带大家了解了《为何 gin 的 SetCookie 方法在添加新 cookie 时不修改旧 cookie?》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>