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.
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})
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
.
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) } }
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!