You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Go中通过graphql-go解析器获取GraphQL查询的操作名称?

获取GraphQL解析后的操作类型与名称

要从解析返回的*ast.Document中提取操作相关信息,需要对Definitions数组中的节点做类型断言,具体步骤如下:

  1. 遍历p.Definitions,将每个节点断言为*ast.OperationDefinition(跳过片段定义等非操作节点)
  2. 操作类型(如subscription/query/mutation)对应Operation字段,直接转为字符串即可
  3. 操作名称(示例中的event)对应Name.Value属性(注意判断Name是否为nil)

以下是完整代码示例:

import (
    "github.com/graphql-go/graphql/language/ast"
    "github.com/graphql-go/graphql/language/parser"
)

func main() {
    query := "subscription event {event(on: \"xxxx\") {msg    __typename  }}"
    p, err := parser.Parse(parser.ParseParams{Source: query})
    if err != nil {
        panic(err)
    }

    for _, def := range p.Definitions {
        opDef, isOp := def.(*ast.OperationDefinition)
        if !isOp {
            continue
        }

        // 获取操作类型(subscription)
        opType := string(opDef.Operation)
        // 获取操作名称(event)
        opName := ""
        if opDef.Name != nil {
            opName = opDef.Name.Value
        }

        // 输出结果
        println("操作类型:", opType)
        println("操作名称:", opName)
    }
}

注:你提到的示例中,subscription是操作类型,event是官方定义的操作名称,若你实际需要的是操作类型,直接使用opType即可。

内容的提问来源于stack exchange,提问作者Joey Yi Zhao

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 22:45:35