Golang中如何调用GraphQL解析器
Golang中如何调用GraphQL解析器 我有一个GraphQL端点(145.75.86.11:7545/graphql),需要调用GraphQL解析器(resolverExample)并发送字符串(“HELLO WORLD”),该如何实现?
1 回复
更多关于Golang中如何调用GraphQL解析器的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
在Golang中调用GraphQL端点可以通过标准库net/http或第三方库如github.com/machinebox/graphql实现。以下是使用标准库的示例:
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
// GraphQL请求结构体
type GraphQLRequest struct {
Query string `json:"query"`
Variables map[string]interface{} `json:"variables,omitempty"`
}
func main() {
endpoint := "http://145.75.86.11:7545/graphql"
// 构建GraphQL查询
query := `
mutation {
resolverExample(input: "HELLO WORLD") {
response
}
}`
req := GraphQLRequest{
Query: query,
}
// 序列化请求体
reqBody, err := json.Marshal(req)
if err != nil {
panic(err)
}
// 创建HTTP请求
httpReq, err := http.NewRequest("POST", endpoint, bytes.NewBuffer(reqBody))
if err != nil {
panic(err)
}
// 设置请求头
httpReq.Header.Set("Content-Type", "application/json")
// 发送请求
client := &http.Client{}
resp, err := client.Do(httpReq)
if err != nil {
panic(err)
}
defer resp.Body.Close()
// 处理响应
var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)
fmt.Printf("响应: %+v\n", result)
}
如果使用github.com/machinebox/graphql库:
package main
import (
"context"
"fmt"
"log"
"github.com/machinebox/graphql"
)
func main() {
client := graphql.NewClient("http://145.75.86.11:7545/graphql")
req := graphql.NewRequest(`
mutation {
resolverExample(input: "HELLO WORLD") {
response
}
}`)
var respData map[string]interface{}
if err := client.Run(context.Background(), req, &respData); err != nil {
log.Fatal(err)
}
fmt.Printf("响应: %+v\n", respData)
}
注意:实际查询结构(mutation/query)和字段名称需根据GraphQL服务端的schema确定。示例假设resolverExample是一个mutation操作,接受字符串参数并返回包含response字段的对象。

