登录
首页 >  Golang >  Go问答

使用 shurcooL/graphql 或 hasura/go-graphql-client 包在 Go 中设置标头键和值的方法

来源:stackoverflow

时间:2024-03-01 08:36:20 204浏览 收藏

目前golang学习网上已经有很多关于Golang的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《使用 shurcooL/graphql 或 hasura/go-graphql-client 包在 Go 中设置标头键和值的方法》,也希望能帮助到大家,如果阅读完后真的对你学习Golang有帮助,欢迎动动手指,评论留言并分享~

问题内容

所以我想使用 shurcool 或 hasura go 客户端(Go 包)通过 Go 从 Graphql 服务器查询数据,但数据服务器需要像“x-hasura-admin-secret”键和值包含在请求标头中.

两个包文档中都没有提到如何执行此操作(设置标头键和值),仅提到如何设置访问令牌。


正确答案


https://github.com/hasura/go-graphql-client 提供的客户端 有一个 withrequestmodifier 方法。您可以添加一个请求标头,如下所示:

import (
    "net/http"
    graphql "github.com/hasura/go-graphql-client"
)

func gqlinit() {
    client := graphql.newclient("your graphql url here", nil)
    client = client.withrequestmodifier(func(r *http.request) {
        r.header.set("x-hasura-admin-secret", "secret")
    })
}

查看https://github.com/shurcool/graphql和相关的github lib,看起来他们希望你传递一个 *http.client 来为你添加标头,你可以这样做:

import (
    "net/http"
    graphql "github.com/shurcooL/graphql"
)

type hasuraAuthTransport struct {
    secret string
}

func (h hasuraAuthTransport) RoundTrip(req *http.Request) (resp *http.Response, err error) {
    req.Header.Set("x-hasura-admin-secret", h.secret)
    return http.DefaultTransport.RoundTrip(req)
}

func gqlInit() {
    client := graphql.NewClient("your graphql url here", &http.Client{
        Transport: hasuraAuthTransport{secret: "secret"},
    })
}

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

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