欢迎光临
我们一直在努力

如何使用 go 包设置标头键和值:shurcooL/graphql 或 hasura/go-graphql-client?

如何使用 go 包设置标头键和值:shurcool/graphql 或 hasura/go-graphql-client?

问题内容

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

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

正确答案

https://www.codesou.cn/link/b93f552915e01e40fb9b66d6fd114f7b 提供的客户端 有一个 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://www.codesou.cn/link/3a5f9129110203548b21c0e40e9cd7af和相关的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"},
    })
}
赞(0) 打赏
未经允许不得转载:码农资源网 » 如何使用 go 包设置标头键和值:shurcooL/graphql 或 hasura/go-graphql-client?
分享到

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续提供更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫打赏

微信扫一扫打赏

登录

找回密码

注册