Go:go-graphql-client(支持查询/变更/订阅的客户端)
graphql-github-io-zh-Hans生态项目与库
Go:go-graphql-client(支持查询/变更/订阅的客户端)
简介
go-graphql-client 是一个轻量级、类型安全的 GraphQL 客户端,专为 Go 语言设计。它支持 GraphQL 的三种核心操作:查询(Query)、变更(Mutation) 和 订阅(Subscription),帮助开发者以简洁、声明式的方式与 GraphQL API 进行交互。
该项目最初由 Hasura 维护,代码托管于 GitHub:https://github.com/hasura/go-graphql-client。
功能特性
- ✅ 支持标准 GraphQL 查询与变更
- ✅ 支持基于 WebSocket 的订阅(需配合支持订阅的 GraphQL 服务端)
- ✅ 类型安全:通过 Go 结构体定义查询形状,编译期校验字段类型
- ✅ 支持自定义 HTTP 头(如认证令牌)
- ✅ 内置文件上传支持(适用于 multipart 请求)
- ✅ 兼容
context.Context,便于超时控制与取消 - ✅ 零第三方依赖,基于标准库实现
安装
使用 go get 获取最新版本:
bash
go get github.com/hasura/go-graphql-client
快速开始
1. 定义 GraphQL 查询结构
假设你的 GraphQL API 提供以下查询:
graphql
{
user(id: "1") {
name
age
}
}
在 Go 中定义对应的结构体:
go
type User struct {
Name string
Age int
}
type query struct {
User User `graphql:"user(id: $id)"`
}
2. 发起查询
go
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/hasura/go-graphql-client"
)
func main() {
client := graphql.NewClient("https://api.example.com/graphql", nil)
var q struct {
User User `graphql:"user(id: $id)"`
}
variables := map[string]interface{}{
"id": "1",
}
err := client.Query(context.Background(), &q, variables, graphql.OperationName("GetUser"))
if err != nil {
log.Fatal(err)
}
fmt.Printf("User: %s (%d)\n", q.User.Name, q.User.Age)
}
3. 执行变更(Mutation)
go
var m struct {
CreateUser struct {
ID string
Name string
} `graphql:"createUser(input: $input)"`
}
input := map[string]interface{}{
"name": "Alice",
}
err := client.Mutate(context.Background(), &m, map[string]interface{}{
"input": input,
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Created user: %s\n", m.CreateUser.ID)
4. 订阅(Subscription)
订阅需要与服务端建立 WebSocket 连接。使用 graphql.NewSubscriptionClient:
go
subClient := graphql.NewSubscriptionClient("wss://api.example.com/graphql")
var sub struct {
MessageAdded struct {
Content string
} `graphql:"messageAdded(roomId: $roomId)"`
}
_, err := subClient.Subscribe(&sub, map[string]interface{}{
"roomId": "general",
}, func(data []byte, err error) error {
if err != nil {
fmt.Println("Subscription error:", err)
return nil
}
fmt.Printf("New message: %s\n", string(data))
return nil
})
if err != nil {
log.Fatal(err)
}
// 保持连接
select {}
自定义请求头
go
client := graphql.NewClient("https://api.example.com/graphql", nil)
client = client.WithRequestHeader("Authorization", "Bearer your-token")
// 或通过 context 传递
ctx := context.WithValue(context.Background(), graphql.RequestHeader, http.Header{
"X-Custom": {"value"},
})
client.Query(ctx, &q, nil)
文件上传
go
file, _ := os.Open("avatar.png")
defer file.Close()
var m struct {
UploadFile struct {
URL string
} `graphql:"uploadFile(file: $file)"`
}
err := client.Mutate(context.Background(), &m, map[string]interface{}{
"file": graphql.Upload{
File: file,
Filename: "avatar.png",
ContentType: "image/png",
},
})
更多资源
- GitHub 仓库:hasura/go-graphql-client
- Go 文档:pkg.go.dev
- 示例代码:examples
通过 go-graphql-client,你可以在 Go 项目中轻松集成 GraphQL API,享受类型安全与完整的操作支持。
帮助我们改进文档
发现翻译问题或内容错误?请告诉我们。
