登录
首页 >  Golang >  Go问答

gqlgen 解析器中设置 cookie

来源:stackoverflow

时间:2024-03-08 21:18:22 391浏览 收藏

golang学习网今天将给大家带来《gqlgen 解析器中设置 cookie》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习Golang或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!

问题内容

我正在使用 gin 和 gqlgen。 我需要从解析器设置 cookie,但我的解析器中只有上下文和来自 graphql 的输入。 这个问题在github上已经有答案了。 但这一个不同,因为当您尝试传入 ctx.next 时,我无法更改 ctx.writer.write 并且什么也没有。因为 gin 不能那样工作。

func (r *mutationResolver) Login(ctx context.Context, email string, password string) (bool, error) {
        // You need ctx.Writer to set a cookie and can't access that from here
}

我已经解决了这个问题,我想在下面回答我自己的问题。


解决方案


说明

How serverside cookie works:

服务器端 cookie 由服务器嵌入到响应标头中,向浏览器发出设置 cookie 的意图。此机制旨在直接在解析器中使用 ctx.writer,从而绕过中间件干预的需要。

在中间件中,为您提供了一个上下文 (ctx),其中包含 ctx.request.context()。您还可以访问 ctx.writer,这是修改标头以设置 cookie 所必需的。要使 ctx.writer 在解析器中可用,您应该将其嵌入到 ctx.request.context() 中。此方法至关重要,因为只有 ctx.request 会传递到解析器,而不是整个上下文 (ctx)。

代码


此结构将用于在中间件中创建并将其指针传递给解析器,在所有路由中您将知道用户是否经过身份验证,并且还能够使用 http.responsewriter p>

结构

type cookieaccess struct {
    writer     http.responsewriter
    isloggedin bool
    userid     uint64
}

中间件

func setvalinctx(ctx *gin.context, val interface{}) {
    newctx := context.withvalue(ctx.request.context(), "ctxcookieaccesskey", val)
    ctx.request = ctx.request.withcontext(newctx)
}

func middleware() gin.handlerfunc {
    return func(ctx *gin.context) {
        cookiea := cookieaccess{
            writer: ctx.writer,
            isloggedin: false, // assume not logged in by default
            userid: 0,
        }

        setvalinctx(ctx, &cookiea)

        c, err := ctx.request.cookie("tokenkey")
        if err != nil {
            // if there's an error fetching the cookie, log it and proceed
            log.printf("error fetching 'tokenkey' cookie: %v", err)
            ctx.next()
            return
        }

        // proceed with token parsing only if the cookie is successfully fetched
        rawtoken := c.value
        userid, err := parsetoken(rawtoken)
        if err != nil {
            // if there's an error parsing the token, log it and ensure user is not logged in
            log.printf("error parsing token: %v", err)
        } else {
            // if token is successfully parsed, mark user as logged in and set userid
            cookiea.isloggedin = true
            cookiea.userid = userid
        }

        ctx.next()
    }
}

解析器

func (r *MutationResolver) logginOrConsumerResolver(ctx context.Context, input Credentials) (*Response, error) {
    // ctx.Request.Context() from middleware is here
    ca := ctx.Value("ctxCookieAccessKey").(*CookieAccess)
    if ca.IsLoggedIn {
        // this is the way to get token proceed result in other resolvers
        return nil, fmt.Errorf("you are already have a valid token, userId: %v", ca.userId)
    }

    http.SetCookie(ca.Writer, &http.Cookie{
        Name:     "tokenKey",
        Value:    token, // make your token
        HttpOnly: true,
        Path:     "/",
        Expires:  time.Now().Add(24 * time.Hour),
    })

    return nil, nil
}

以上就是《gqlgen 解析器中设置 cookie》的详细内容,更多关于的资料请关注golang学习网公众号!

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