GraphQL Operation Header in GO
Match GraphQL operation headers — `query`, `mutation`, or `subscription` — capturing the operation name.
Try it in the GO tester →Pattern
regexGO
(query|mutation|subscription)\s+(\w+)?\s*(?:\([^)]*\))?\s*\{ (flags: g)Go (RE2) code
goGo
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`(query|mutation|subscription)\s+(\w+)?\s*(?:\([^)]*\))?\s*\{`)
input := `query GetUser($id: ID!) { user(id: $id) { name } }`
for _, match := range re.FindAllString(input, -1) {
fmt.Println(match)
}
}Uses `regexp.MustCompile` (panics on bad patterns at startup) and `FindAllString` for all matches.
How the pattern works
(query|mutation|subscription) captures the operation type. \s+(\w+)? optionally captures the operation name (anonymous operations omit it). (?:\([^)]*\))? optionally matches a variables declaration `($var: Type)`. The trailing `\s*\{` matches the opening brace of the selection set.
Examples
Input
query GetUser($id: ID!) { user(id: $id) { name } }Matches
query GetUser($id: ID!) {
Input
mutation { createPost(title: "hi") { id } }Matches
mutation {
Input
// not graphqlNo match
—