Go:machinebox/graphql(低层 HTTP 客户端)
graphql-github-io-zh-Hans生态项目与库
Go:machinebox/graphql(低层 HTTP 客户端)
machinebox/graphql 是一个优雅的低层 GraphQL HTTP 客户端,致力于为 Go 项目提供简洁、直接的 GraphQL over HTTP 交互方式。它不包含缓存、订阅等高级功能,而是聚焦于请求构造、变量绑定和响应解码,非常适合作为微服务或工具库中的基础 GraphQL 客户端。
功能特性
- 轻量级,仅封装 GraphQL over HTTP 核心逻辑
- 支持 Query 和 Mutation
- 支持自定义 HTTP Header(如鉴权信息)
- 通过
Var方法安全地传递请求变量 - 原生支持
context.Context,便于超时和取消控制 - 支持自定义底层
http.Client,方便集成连接池、重试等机制
安装
使用 go get 获取:
bash
go get github.com/machinebox/graphql
快速开始
1. 创建客户端
go
import (
"context"
"fmt"
"log"
"github.com/machinebox/graphql"
)
func main() {
client := graphql.NewClient("https://api.example.com/graphql")
// 可选的初始化...
}
如果需要自定义 HTTP Client:
go
httpClient := &http.Client{Timeout: 10 * time.Second}
client := graphql.NewClient("https://api.example.com/graphql", graphql.WithHTTPClient(httpClient))
2. 构造请求
go
req := graphql.NewRequest(`
query ($username: String!) {
user(username: $username) {
id
name
}
}
`)
// 设置变量
req.Var("username", "gopher")
// 设置 Header
req.Header.Set("Authorization", "Bearer your-token")
3. 执行请求并解码响应
go
var resp struct {
User struct {
ID string `json:"id"`
Name string `json:"name"`
} `json:"user"`
}
if err := client.Run(context.Background(), req, &resp); err != nil {
log.Fatal(err)
}
fmt.Printf("用户ID: %s\n", resp.User.ID)
fmt.Printf("用户名: %s\n", resp.User.Name)
核心 API
| 方法 / 类型 | 说明 |
|---|---|
graphql.NewClient(endpoint string, opts ...ClientOption) |
创建一个指向指定端点的 GraphQL 客户端 |
client.Run(ctx context.Context, req *Request, resp interface{}) error |
执行请求,并将响应数据解码到 resp 中;若 GraphQL 返回错误,则返回 error |
graphql.NewRequest(query string) |
根据 GraphQL 查询字符串创建请求对象 |
req.Var(key string, value interface{}) |
设置用于查询的变量值 |
req.Header |
提供对 HTTP 请求头的直接访问 |
注意事项
- 该库只负责低层请求与响应处理,不提供订阅(Subscription)、客户端缓存或批量请求功能。
- 变量值必须是 JSON 可序列化类型,库内部会使用
encoding/json处理。 - 响应中的
errors字段会作为 Go 错误返回,建议在调用Run后先检查错误。 - 由于是低层客户端,你可以很轻松地用
httptest构造模拟服务进行单元测试。
参考链接
- GitHub 仓库:machinebox/graphql
- 项目地址:https://github.com/machinebox/graphql
帮助我们改进文档
发现翻译问题或内容错误?请告诉我们。
