Complete GraphQL implementation in Go with schema definition, query execution, and validation.
go get github.com/graphql-go/graphqlpackage main
import (
"encoding/json"
"fmt"
"github.com/graphql-go/graphql"
)
func main() {
// 1. Define a simple type
fields := graphql.Fields{
"hello": &graphql.Field{
Type: graphql.String,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return "world", nil
},
},
}
// 2. Create root query type
rootQuery := graphql.ObjectConfig{Name: "RootQuery", Fields: fields}
// 3. Create schema
schemaConfig := graphql.SchemaConfig{Query: graphql.NewObject(rootQuery)}
schema, err := graphql.NewSchema(schemaConfig)
if err != nil {
panic(err)
}
// 4. Execute a query
result := graphql.Do(graphql.Params{
Schema: schema,
RequestString: `{ hello }`,
})
// 5. Handle results
if result.HasErrors() {
fmt.Printf("errors: %v\n", result.Errors)
return
}
// 6. Output data
json.NewEncoder(os.Stdout).Encode(result.Data)
// Output: {"hello":"world"}
}fields := graphql.Fields{
"user": &graphql.Field{
Type: graphql.String,
Args: graphql.FieldConfigArgument{
"id": &graphql.ArgumentConfig{
Type: graphql.NewNonNull(graphql.String),
},
},
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
id := p.Args["id"].(string)
return fmt.Sprintf("User %s", id), nil
},
},
}
// Query: { user(id: "123") }result := graphql.Do(graphql.Params{
Schema: schema,
RequestString: `query GetUser($id: String!) { user(id: $id) }`,
VariableValues: map[string]interface{}{
"id": "123",
},
})import "context"
// Pass context
ctx := context.WithValue(context.Background(), "requestID", "req-123")
result := graphql.Do(graphql.Params{
Schema: schema,
Context: ctx,
})
// Access in resolver
resolve: func(p graphql.ResolveParams) (interface{}, error) {
requestID := p.Context.Value("requestID").(string)
// Use requestID for logging, tracing, etc.
return data, nil
}Install with Tessl CLI
npx tessl i tessl/golang-github-com--graphql-go--graphqldocs