英文:
How to set header key and value with go packages : shurcooL/graphql or hasura/go-graphql-client?
问题
所以我想使用Go和shurcool或hasura go客户端(Go包)从Graphql服务器查询数据,但是数据服务器需要类似于'x-hasura-admin-secret'的键和值包含在请求头中。
在这两个包的文档中都没有提到如何做到这一点(设置头部键和值),它们只提到了如何设置访问令牌。
英文:
So I want to query datas from Graphql server via Go with either shurcool or hasura go client (Go packages), but the datas server required something like 'x-hasura-admin-secret' key and value includes inside a request header.<br>
There's no mentioned in the both packages docs of how to do this (set header key & value), it only mentioned how to set access token.
答案1
得分: 1
由于您的请求是要求我进行翻译,我将为您翻译以下内容:
来自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"},
})
}
英文:
The client provided by https://github.com/hasura/go-graphql-client has a WithRequestModifier
method. You could add a request header like so:
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")
})
}
Looking at https://github.com/shurcooL/graphql and the related github lib, it seems like they expect you to pass an *http.Client
that will add the header for you, you could do that like so:
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"},
})
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论