Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set header key and value with go packages : shurcooL/graphql or hasura/go-graphql-client?

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.

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.

like image 871
Jackk-Doe Avatar asked Oct 31 '25 07:10

Jackk-Doe


1 Answers

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"},
    })
}
like image 65
maxm Avatar answered Nov 03 '25 08:11

maxm