Golang中如何发起GraphQL请求
Golang中如何发起GraphQL请求 我需要在Go语言中发起GraphQL请求
以下是我想要使用的GraphQL mutation:
mutation aki($desc: String!, $ty: String!, $id: Int!){
createProfileOrder(userId: $id, description: $desc, type: $ty){
orderId
}
}
我正在尝试这样做:
num := 1
te := "test"
types := "Fi"
str := fmt.Sprintf(`{"query": "mutation{createProfileOrder(userId: %d, description: %s , type: %s){orderId} }"}`, num, te, types)
body := strings.NewReader(str)
fmt.Println(str)
req, err := http.NewRequest("POST", "http://188.26.69.11/graphql/", body)
if err != nil {
log.Println(err)
}
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Println(err)
}
defer resp.Body.Close()
log.Println(resp)
但是它返回错误:
错误请求 400 HTTP
更多关于Golang中如何发起GraphQL请求的实战教程也可以访问 https://www.itying.com/category-94-b0.html
5 回复
很遗憾我无法访问服务器日志!
哦,是的,你说得对,问题出在类型上。我已经修改了它们,现在工作正常了,谢谢!
构建请求体的方式如下:
package main
import (
"fmt"
)
func main() {
num := 1
te := "test"
types := "Fi"
str := fmt.Sprintf(`{"query": "mutation{createProfileOrder(userId: %d, description: %s , type: %s){orderId} }"}`, num, te, types)
fmt.Println(str)
}
https://play.golang.com/p/ZYtA0a1FhZn
这会输出以下结果:
{"query": "mutation{createProfileOrder(userId: 1, description: test , type: Fi){orderId} }"}
description和type的参数值不应该是字符串字面量吗?还有orde4rId是怎么回事?GraphQL会接受这样的请求体吗?
在Go中发起GraphQL请求时,需要正确格式化GraphQL查询并使用变量传递参数。你的代码存在几个问题:字符串值没有用引号包裹,缺少变量定义,且Content-Type可能需要明确指定为application/json。
以下是修正后的示例代码:
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
)
// GraphQL请求结构体
type GraphQLRequest struct {
Query string `json:"query"`
Variables map[string]interface{} `json:"variables"`
}
func main() {
url := "http://188.26.69.11/graphql/"
// 定义GraphQL mutation和变量
query := `
mutation aki($desc: String!, $ty: String!, $id: Int!) {
createProfileOrder(userId: $id, description: $desc, type: $ty) {
orderId
}
}
`
variables := map[string]interface{}{
"desc": "test",
"ty": "Fi",
"id": 1,
}
// 构建请求体
requestBody := GraphQLRequest{
Query: query,
Variables: variables,
}
// 序列化为JSON
jsonData, err := json.Marshal(requestBody)
if err != nil {
log.Fatal("JSON序列化错误:", err)
}
// 创建HTTP请求
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
log.Fatal("创建请求错误:", err)
}
req.Header.Set("Content-Type", "application/json")
// 发送请求
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatal("请求错误:", err)
}
defer resp.Body.Close()
// 处理响应
var result map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
log.Fatal("解析响应错误:", err)
}
fmt.Printf("响应状态: %d\n", resp.StatusCode)
fmt.Printf("响应数据: %+v\n", result)
}
这个实现:
- 使用结构体定义GraphQL请求格式
- 正确使用变量传递参数,避免字符串拼接问题
- 确保JSON正确序列化
- 添加了响应解析逻辑
如果服务器需要认证,你可能还需要添加Authorization头:
req.Header.Set("Authorization", "Bearer your-token-here")
对于更复杂的GraphQL操作,可以考虑使用专门的GraphQL客户端库如graphql-go/graphql或shurcooL/graphql。

