我正在使用杜松子酒。我有一个从 cookie 中提取令牌的函数,它确实有效。我在路由处理程序中使用此函数并想测试处理程序函数,但我不知道如何。功能:// Extracts token from a cookiefunc tokenFromCookie(c *gin.Context, name string) (string, error) { token, err := c.Cookie(name) if err != nil { return "", err } return token, nil}路线:func RefreshTokenHandler(accessTokenKey string, refreshTokenKey string) gin.HandlerFunc {fn := func(c *gin.Context) { token, err := tokenFromCookie(c, "refresh_token") if err != nil { _ = c.Error(err).SetMeta(noCookie) return } c.JSON(http.StatusOK, gin.H{ "token": token, })})路线定义:func CreateRoutes(r *gin.Engine) *gin.Engine { r.Use(errorHandler) // Auth auth := r.Group("/auth") { auth.GET("/refresh-token", RefreshTokenHandler(accessTokenSignatureKey, refreshTokenSignatureKey)) } return r}单元测试:func TestRefreshTokenHandler(t *testing.T) { req, _ := http.NewRequest("GET", "/auth/refresh-token", nil) req.AddCookie(&http.Cookie{ Name: "refresh_token", Value: "token", MaxAge: 604800, Expires: time.Now().Add(time.Hour * 24 * 7), Path: "/", Domain: "127.0.0.1", HttpOnly: true, SameSite: http.SameSiteNoneMode, Secure: secure } ) w := httptest.NewRecorder() router.ServeHTTP(w, req) got := w.Code if gotCode != 200 { t.Errorf("GET /auth/refresh-token; got %d, want 200", got) }}tokenFromCookie ()函数虽然会引发错误:http: named cookie not present这是我在gin gonic repo中发现的一个类似的单元测试:func TestContextGetCookie(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Request, _ = http.NewRequest("GET", "/get", nil) c.Request.Header.Set("Cookie", "user=gin") cookie, _ := c.Cookie("user") assert.Equal(t, "gin", cookie) _, err := c.Cookie("nokey") assert.Error(t, err)}但是我不明白为什么我的代码不起作用以及如何重写它。
1 回答
侃侃尔雅
TA贡献1801条经验 获得超15个赞
要查看列表 cookie,您可以尝试以下操作:
fmt.Println(c.Request.Cookies())
我不明白创建新函数 tokenFromCookie 的意义。
func RefreshTokenHandler(accessTokenKey string, refreshTokenKey string) gin.HandlerFunc {
fn := func(c *gin.Context) {
//token, err := tokenFromCookie(c, "refresh_token")
token, err := c.Cookie("refresh_token")
if err != nil {
_ = c.Error(err).SetMeta(noCookie)
return
}
c.JSON(http.StatusOK, gin.H{
"token": token,
})
})
- 1 回答
- 0 关注
- 167 浏览
添加回答
举报
0/150
提交
取消