卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章33972本站已运行390

如何使用 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.php.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.php.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"},
    })
}
卓越飞翔博客
上一篇: 带有 golang 的 Lambda 自定义 al2 运行时,初始化阶段超时
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏