Created
November 2, 2016 18:32
-
-
Save rms1000watt/ba8db3137905b0848a4236e5f31125e3 to your computer and use it in GitHub Desktop.
Golang GraphQL Client
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I don't think you have to convert the
requestString
to byte array. The following change works too.