Home > Backend Development > Golang > How to parse graphql query to get operation name in go?

How to parse graphql query to get operation name in go?

PHPz
Release: 2024-02-09 13:57:08
forward
1039 people have browsed it

如何解析 graphql 查询以获取 go 中的操作名称?

php editor Baicao introduces you how to parse GraphQL queries to obtain operation names in Go. GraphQL is a query language used to obtain and modify data. In Go language, we can use some libraries to parse GraphQL queries and extract operation names. The specific steps are to first parse the GraphQL query string, then obtain the root node, and then traverse the child nodes of the root node to determine whether the node type is an operation type. If so, obtain the operation name. In this way, we can easily extract the operation name in Go from the GraphQL query for subsequent processing and operation.

Question content

I am using this go library to parse graphql query strings: github.com/graphql-go/graphql/language/parser.

I have the following code:

query := "subscription event {event(on: "xxxx") {msg    __typename  }}"
p, err := parser.Parse(parser.ParseParams{Source: query})
Copy after login

The returned p is an instance of *ast.document. p There is a definitions field, which is an ast.node[] array.

But I don't know how to get the operation name from the query. In this case it would be subscription.

Solution

Because p.definitions is part of node, and node is the interface implemented by ast.operationdefinition.

So, in order to extract the data of the operationdefinition node, you need to perform an assertion.

for _, d := range p.Definitions {
    if oper, ok := d.(*ast.OperationDefinition); ok {
        fmt.Println(oper.Operation)
    }
}
Copy after login

The above is the detailed content of How to parse graphql query to get operation name in go?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template