Skip to content

Instantly share code, notes, and snippets.

@pedrobertao
Last active September 17, 2022 11:58
Show Gist options
  • Save pedrobertao/c29af99213cddc309bffee504e427898 to your computer and use it in GitHub Desktop.
Save pedrobertao/c29af99213cddc309bffee504e427898 to your computer and use it in GitHub Desktop.
Raw HTTP request to a GraphQL server
package main
import (
"bytes"
"encoding/json"
"io/ioutil"
"log"
"net/http"
"os"
"time"
)
type GraphQLRequest struct {
Query string `json:"query"`
Variables map[string]interface{} `json:"variables"`
}
// GraphQLResponse based on the server response
type GraphQLResponse struct {
Data struct {
Country struct {
Name string `json:"name"`
Currency string `json:"currency"`
Phone string `json:"phone"`
} `json:"country"`
} `json:"data"`
}
func main() {
// Build the request without using third party packages
// For this example we're using a public Country API that returns
// basic data from countries
gqlReq := GraphQLRequest{
Query: `
query GetCountry($countryCode: ID!) {
country(code: $countryCode) {
name
currency
phone
}
}
`,
Variables: map[string]interface{}{
"countryCode": "BR",
},
}
// Encode request
var requestBody bytes.Buffer
if err := json.NewEncoder(&requestBody).Encode(gqlReq); err != nil {
log.Fatal(err)
}
// By default, all gql requests are POSTs to
// https://<YOUR_GRAPHQL_URL>/query
url := "https://countries.trevorblades.com/query"
req, err := http.NewRequest(http.MethodPost, url, &requestBody)
if err != nil {
log.Fatal(err)
}
// Default Headers
req.Header.Set("Content-Type", "application/json; charset=utf-8")
req.Header.Set("Accept", "application/json; charset=utf-8")
// Make the request with timeout
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
// Decode request response
var response GraphQLResponse
err = json.Unmarshal(body, &response)
if err != nil {
log.Fatal(err)
}
// Log Response
log.Println(response) // {{{Brazil BRL 55}}}
os.Exit(0)
}
@thaiquancut
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment