生产环境首选 graphql-go/graphql 库,它成熟稳定、兼容 GraphQL v15+,支持 SDL schema、字段解析器、上下文透传和精准错误定位,而 graph-gophers/graphql-go 旧版已停更且不支持 @defer/@stream。
生产环境首选 graphql-go/graphql,它是最成熟的 Go GraphQL 实现,兼容 GraphQL 规范 v15+,支持 schema SDL 定义、字段解析器、上下文透传和错误定位。别用 graph-gophers/graphql-go 的旧分支(如 v0.9.x),它已停止维护且不支持 @defer 和 @stream 等现代特性。
schema 必须用字符串写成 SDL 格式,不能靠结构体反射自动生成——否则丢失参数类型、默认值和描述信息,调试时错误提示极差。resolver 函数签名必须严格匹配:func(p graphql.ResolveParams) (interface{}, error)。
var schema, _ = graphql.NewSchema(graphql.SchemaConfig{
Query: graphql.NewObject(graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"user": &graphql.Field{
Type: userType,
Args: graphql.FieldConfigArgument{
"id": &graphql.ArgumentConfig{Type: graphql.Int},
},
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
id, ok := p.Args["id"].(int)
if !ok {
return nil, fmt.Errorf("id must be int")
}
return findUserByID(id), nil
},
},
},
}),
})
Args 值默认是 interface{},必须显式类型断言,graphql.Int 不代表 Go 的 int,而是 GraphQL 类型;实际值可能是 int32 或 float64(来自 JSON 解析)userType 必须提前用 graphql.NewObject 构建,不能现场内联——否则 schema 验证失败nil 且无 error 不等于“空结果”,GraphQL 会把它当 null 字段处理;想表示缺失,应返回 nil, nil
GraphQL 只接受 POST /graphql,且要求 Content-Type: application/json。直接用 http.HandleFunc 处理时,必须完整读取 body、解析 JSON、调用 graphql.Do,再手动序列化响应——任何中间步骤出错都会导致 500 或空响应。
http.HandleFunc("/graphql", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var req struct {
Query string `json:"query"`
Variables map[string]interface{} `json:"variables,omitempty"`
OperationName string `json:"operationName,omitempty"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
result := graphql.Do(graphql.Params{
Schema: schema,
RequestString: req.Query,
VariableValues: req.Variables,
OperationName: req.OperationName,
Context: r.Context(),
})
json.NewEncoder(w).Encode(result)
})
OperationName,否则带多个命名操作的 query 会执行失败Variables 是 map[string]interface{},但 GraphQL resolver 里收到的仍是 map[string]interface{},Go 类型不会自动转换;比如前端传 {"limit": 10},resolver 中 p.Args["limit"] 是 float64,不是 int
json.Encoder 直接写入 w,不要先拼字符串再 w.Write,否则可能丢 header 或触发 chunked 编码异常因为 graphql.Do 默认不把 http.Request 注入 resolver 上下文。必须手动把 r 或提取的关键字段(如 Authorization、X-Request-ID)塞进 context.Context,再通过 params.Info.RootValue 或自定义 context key 传递。
立即学习“go语言免费学习笔记(深入)”;
// 在 handler 中:
ctx := context.WithValue(r.Context(), "auth_token", r.Header.Get("Authorization")
)
result := graphql.Do(graphql.Params{
Context: ctx,
// ...
})
// 在 resolver 中:
token := params.Context.Value("auth_token").(string)
http.Request 方法——params.Context 是唯一合法入口context.WithValue 时,key 类型必须是 unexported struct 或私有类型,避免和其他库冲突;用字符串 key 在大型项目中极易覆盖*http.Request;Gin 的 c.Request 是可用的,但需显式传入