CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/golang-github-com--graphql-go--graphql

Complete GraphQL implementation in Go with schema definition, query execution, and validation.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

graphql-go/graphql

A complete GraphQL implementation in Go following the official reference implementation. Supports queries, mutations, subscriptions, schema definition, validation, and execution.

Installation

go get github.com/graphql-go/graphql

Quick Start

import "github.com/graphql-go/graphql"

// 1. Define schema
schema, _ := graphql.NewSchema(graphql.SchemaConfig{
    Query: graphql.NewObject(graphql.ObjectConfig{
        Name: "RootQuery",
        Fields: graphql.Fields{
            "hello": &graphql.Field{
                Type: graphql.String,
                Resolve: func(p graphql.ResolveParams) (interface{}, error) {
                    return "world", nil
                },
            },
        },
    }),
})

// 2. Execute query
result := graphql.Do(graphql.Params{
    Schema:        schema,
    RequestString: `{ hello }`,
})

Full Quick Start Guide →

Core Capabilities

CapabilityDescriptionReference
Schema DefinitionDefine types, interfaces, unions, enums, and scalarsSchema →
Query ExecutionExecute queries and mutations with variablesExecution →
SubscriptionsReal-time updates via subscription operationsExecution →
ValidationValidate documents against schema rulesValidation →
AST & ParsingParse GraphQL to AST, traverse and transformLanguage →
Error HandlingStructured errors with location infoErrors →

Key APIs

Schema Creation

func NewSchema(config SchemaConfig) (Schema, error)
func NewObject(config ObjectConfig) *Object
func NewInterface(config InterfaceConfig) *Interface
func NewUnion(config UnionConfig) *Union
func NewEnum(config EnumConfig) *Enum
func NewScalar(config ScalarConfig) *Scalar
func NewInputObject(config InputObjectConfig) *InputObject

Query Execution

func Do(p Params) *Result
func Execute(p ExecuteParams) *Result
func Subscribe(p Params) chan *Result
func ExecuteSubscription(p ExecuteParams) chan *Result

Validation

func ValidateDocument(schema *Schema, astDoc *ast.Document, rules []ValidationRuleFn) ValidationResult

Parsing

func Parse(p ParseParams) (*ast.Document, error)
func ParseValue(p ParseParams) (ast.Value, error)

Built-in Types

var Int      *Scalar // 32-bit signed integer
var Float    *Scalar // Double-precision float
var String   *Scalar // UTF-8 text
var Boolean  *Scalar // true/false
var ID       *Scalar // Unique identifier (serialized as string)
var DateTime *Scalar // RFC 3339 date-time string

Type Modifiers

func NewList(ofType Type) *List           // [Type]
func NewNonNull(ofType Type) *NonNull     // Type!

Common patterns:

graphql.NewList(userType)                              // [User]
graphql.NewNonNull(graphql.String)                     // String!
graphql.NewNonNull(graphql.NewList(userType))          // [User]!
graphql.NewList(graphql.NewNonNull(userType))          // [User!]

Context Usage

// Pass context to resolvers
result := graphql.Do(graphql.Params{
    Schema:  schema,
    Context: context.WithValue(ctx, "userID", "123"),
})

// Access in resolver
resolve: func(p graphql.ResolveParams) (interface{}, error) {
    userID := p.Context.Value("userID").(string)
    return fetchUser(userID)
}

Error Handling

Resolvers return (interface{}, error):

resolve: func(p graphql.ResolveParams) (interface{}, error) {
    val, err := fetchData(p.Args["id"])
    if err != nil {
        return nil, err // Becomes FormattedError in Result.Errors
    }
    return val, nil
}

Resources

Important Notes for Agents

Circular References

Use thunks (functions) for fields/interfaces that reference types not yet defined:

var personType = graphql.NewObject(graphql.ObjectConfig{
    Name: "Person",
    Fields: graphql.FieldsThunk(func() graphql.Fields {
        return graphql.Fields{
            "friends": &graphql.Field{Type: graphql.NewList(personType)},
        }
    }),
})

Type Assertions

Arguments come as map[string]interface{} - always type assert:

id := p.Args["id"].(string)
limit := p.Args["limit"].(int)

Nil Handling

The default resolver returns nil for missing fields. Handle appropriately in parent resolvers.

For detailed documentation, see the reference section.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
golangpkg:golang/github.com/graphql-go/graphql@v0.8.1
Publish Source
CLI
Badge
tessl/golang-github-com--graphql-go--graphql badge