Skip to content

Instantly share code, notes, and snippets.

@rms1000watt
Created November 2, 2016 18:32
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save rms1000watt/ba8db3137905b0848a4236e5f31125e3 to your computer and use it in GitHub Desktop.
Save rms1000watt/ba8db3137905b0848a4236e5f31125e3 to your computer and use it in GitHub Desktop.
Golang GraphQL Client
package main
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"strconv"
)
const (
URL = "http://www.example.com/graphql"
Cookie = "csrf_token=88a8a8a8a8a8a8a8a8a8a8a8=; token=9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s9s=="
)
func main() {
queries := []string{
`mutation Update {
user_update(
user: {
fname: "John",
lname: "Smith",
},
) {
fname
lname
}
}`,
`query User {
user {
fname
lname
}
}`,
}
for _, query := range queries {
makeRequest(queryToRequest(strconv.QuoteToASCII(query)))
}
}
func queryToRequest(queryString string) string {
return `{"query":` + queryString + `}`
}
func makeRequest(requestString string) {
// http://stackoverflow.com/questions/24455147/how-do-i-send-a-json-string-in-a-post-request-in-go
fmt.Println("URL:", URL)
var str = []byte(requestString)
req, err := http.NewRequest("POST", URL, bytes.NewBuffer(str))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Cookie", Cookie)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println("Status:", resp.Status)
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("Body:", string(body))
}
@Sen-Zhang
Copy link

Sen-Zhang commented Aug 10, 2017

I don't think you have to convert the requestString to byte array. The following change works too.

req, err := http.NewRequest("POST", URL, strings.NewReader(requestString))

@jimmylin212
Copy link

Really helpful, thank you.

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