Home > Backend Development > Golang > How to set header keys and values ​​using go package: shurcooL/graphql or hasura/go-graphql-client?

How to set header keys and values ​​using go package: shurcooL/graphql or hasura/go-graphql-client?

WBOY
Release: 2024-02-05 22:36:11
forward
820 people have browsed it

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

Question content

So I want to use shurcool or hasura go client (Go package) to query data from Graphql server through Go, but the data server needs to be like The "x-hasura-admin-secret" key and value are included in the request header.

There is no mention in either package documentation of how to do this (setting header keys and values), only how to set the access token.


Correct answer


The client provided by https://www.php.cn/link/b93f552915e01e40fb9b66d6fd114f7b has a withrequestmodifier method. You can add a request header like this:

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")
    })
}
Copy after login

Viewhttps://www.php.cn/link/3a5f9129110203548b21c0e40e9cd7af and the related github lib, it looks like they want you to pass a *http.client to add headers for you, you can do this:

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"},
    })
}
Copy after login

The above is the detailed content of How to set header keys and values ​​using go package: shurcooL/graphql or hasura/go-graphql-client?. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template