Generated banner for Golang Graphql
Generated logo for Golang Graphql

Golang Graphql

Samuel BertheCommunityCreated by samberDistributed by Samuel Berthe

  • Skill
  • Tool integration
  • Software development
  • MIT
  • No issues found

From the author

Implements GraphQL APIs in Golang using gqlgen or graphql-go. Apply when building GraphQL servers, designing schemas, writing resolvers, handling subscriptions, or integrating GraphQL with existing Go HTTP services. Also apply when the codebase imports `github.com/99designs/gqlgen` or `github.com/graph-gophers/graphql-go`.
— the description by samber

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill assists developers in building GraphQL servers within the Go ecosystem. It covers the implementation of schemas, resolvers, and subscriptions, while providing specific guidance for the gqlgen and graph-gophers/graphql-go libraries. The skill includes patterns for N+1 query prevention via DataLoaders, authentication, error handling, and schema design, alongside configuration advice for production environments.

What it does

  • Provides best practices for schema-first GraphQL development in Go.
  • Offers guidance on choosing between gqlgen and graph-gophers/graphql-go.
  • Details patterns for implementing DataLoaders to prevent N+1 database query issues.
  • Outlines methods for handling authentication, authorization, and custom error formatting.
  • Provides instructions for managing long-lived subscriptions and WebSocket connections.
  • Includes configuration advice for query complexity limits and introspection.

When to use it

  • When building or maintaining a GraphQL server using Go.
  • When designing GraphQL schemas and mapping them to Go resolvers.
  • When optimizing resolver performance to avoid N+1 database access patterns.
  • When integrating GraphQL APIs with existing Go HTTP services.
  • When configuring gqlgen or graph-gophers/graphql-go for specific project requirements.

Advantages

  • Standardizes GraphQL implementation patterns across Go projects.
  • Helps prevent common pitfalls like goroutine leaks and data leakage.
  • Provides clear guidance on library-specific workflows and configurations.
  • Encourages separation of concerns between domain models and GraphQL resolvers.

Usage examples

“How do I implement a DataLoader for my User posts in gqlgen?”
The agent provides a pattern for creating a per-request DataLoader in HTTP middleware and wiring it into the resolver to batch database queries.
“What is the best way to handle errors in my GraphQL resolvers?”
The agent explains how to use a custom ErrorPresenter or ResolverError interface to mask internal errors and return safe, structured messages to the client.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/samber/golang-graphql/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip golang-graphql.zip -d .agents/skills

Documentation by samber

Persona: You are a Go GraphQL engineer. You design schemas deliberately, batch database access to prevent N+1, and treat query complexity limits as non-optional in production.

Modes:

  • Build mode — generating new schemas, resolvers, or server setup: follow the skill's sequential instructions; launch a background agent to grep for existing resolver patterns and naming conventions before generating new code.

  • Review mode — auditing a GraphQL codebase or PR: use a sub-agent to scan for N+1 resolver patterns, missing complexity caps, global DataLoaders, and introspection enabled in production, in parallel with reading the business logic.

Community default. A company skill that explicitly supersedes samber/cc-skills-golang@golang-graphql skill takes precedence.

Go GraphQL Best Practices

Both major libraries are schema-first: write SDL (.graphql files), bind Go resolvers. Choose based on project size and team preferences.

This skill is not exhaustive — refer to each library's official documentation and code examples for current API signatures:

  • For Go package docs, symbols, versions, importers, and known vulnerabilities, → See samber/cc-skills-golang@golang-pkg-go-dev skill (godig), preferred over Context7 for Go package facts.

  • To navigate this library's usage in your own code (definitions, call sites, diagnostics), → See samber/cc-skills-golang@golang-gopls skill (gopls).

  • Context7 remains a fallback for docs not indexed on pkg.go.dev.

Library Choice

LibraryApproachType safetyBuild stepBest for
github.com/99designs/gqlgenCodegenCompile-timego generateLarge schemas, federation, strict types
github.com/graph-gophers/graphql-goReflectionParse-timeNoneSimple schemas, fast iteration
github.com/graphql-go/graphqlCode-firstRuntimeNoneAvoid — verbose, no SDL

Pick gqlgen when: Apollo Federation is required, schema is large (100+ types), or the team wants generated stubs and zero reflection overhead.

Pick graph-gophers when: schema is small/medium, the build pipeline should stay simple, or a dynamic schema is needed.

For deep-dive on each library, see gqlgen reference and graphql-go reference.

Schema Design

# ✓ Good — explicit nullability; ID scalar for opaque identifiers
type User {
  id: ID!
  email: String! # non-null: the server can always return this
  bio: String # nullable: may be unset
  posts(first: Int = 10, after: String): PostConnection!
}

# ✗ Bad — Int ID leaks implementation details, breaks client caching
type Post {
  id: Int!
}

Nullability rule: mark a field ! only when the server can always return a value. A resolver error on a non-null field nulls the parent object, causing cascade failures; nullable fields only null the field itself.

Pagination: use Relay cursor connections (Connection/Edge/PageInfo) for list fields. Avoid offset pagination on large datasets — cursors are stable under concurrent writes.

Mutations: wrap results in an envelope type so clients receive business errors alongside partial results without polluting the GraphQL errors array:

type CreateUserPayload {
  user: User
  errors: [UserError!]!
}

Resolver Patterns

Keep resolvers thin — they translate GraphQL inputs to domain calls and domain responses to GraphQL outputs.

// ✓ Good — resolver delegates to service layer
func (r *mutationResolver) CreateUser(ctx context.Context, input model.CreateUserInput) (*model.CreateUserPayload, error) {
    user, err := r.userService.Create(ctx, input.Email, input.Name)
    if err != nil {
        return nil, formatError(err)
    }
    return &model.CreateUserPayload{User: toGQLUser(user)}, nil
}

// ✗ Bad — SQL in resolver, no separation of concerns
func (r *queryResolver) User(ctx context.Context, id string) (*model.User, error) {
    row := r.db.QueryRowContext(ctx, "SELECT * FROM users WHERE id = $1", id)
    // ...
}

Use per-type resolver structs (userResolver, postResolver) rather than one monolithic resolver for all fields.

N+1 Prevention (DataLoaders)

Each User.posts resolver fires a SQL query per user without batching — O(n) DB calls for n users. DataLoaders solve this by coalescing per-field loads into a single batch query.

Critical rule: DataLoaders MUST be created per-request in HTTP middleware, never globally. A global DataLoader caches across requests — stale data, potential cross-user data leakage.

// ✓ Good — per-request DataLoader in middleware
func DataLoaderMiddleware(db *sql.DB, next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        loaders := &Loaders{
            PostsByUserID: newPostsByUserIDLoader(r.Context(), db),
        }
        ctx := context.WithValue(r.Context(), loadersKey, loaders)
        next.ServeHTTP(w, r.WithContext(ctx))
    })
}

// ✗ Bad — global DataLoader shared across all requests
var globalLoader = newPostsByUserIDLoader(context.Background(), db)

In gqlgen, mark batched fields with resolver: true in gqlgen.yml to force a dedicated resolver method. See gqlgen reference for full DataLoader wiring.

Authentication and Authorization

Two-layer model:

  1. HTTP middleware — extract and validate tokens, stash identity in context.Context.

  2. Schema directives (gqlgen) or resolver checks (graphql-go) — enforce per-field authorization.

// HTTP middleware layer (both libraries)
func AuthMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        token := r.Header.Get("Authorization")
        user, err := validateToken(token)
        if err != nil {
            http.Error(w, "Unauthorized", http.StatusUnauthorized)
            return
        }
        ctx := context.WithValue(r.Context(), userKey, user)
        next.ServeHTTP(w, r.WithContext(ctx))
    })
}

In gqlgen, use @hasRole schema directives for field-level authorization — authorization policy lives in the schema, not scattered across resolvers. See gqlgen reference.

Error Handling

Never return raw internal errors — they leak SQL messages, stack traces, or service internals to clients.

// gqlgen — custom ErrorPresenter strips internal details
srv.SetErrorPresenter(func(ctx context.Context, err error) *gqlerror.Error {
    var gqlErr *gqlerror.Error
    if errors.As(err, &gqlErr) {
        return gqlErr // already formatted
    }
    // log internal err here
    return gqlerror.Errorf("internal error") // safe client message
})

// Add extension codes for client-side error handling
return nil, &gqlerror.Error{
    Message: "user not found",
    Extensions: map[string]any{"code": "NOT_FOUND"},
}

For graph-gophers, implement the ResolverError interface to attach Extensions(). See graphql-go reference.

Use graphql.AddError(ctx, err) in gqlgen for non-fatal field errors where the resolver can still return partial data.

For error wrapping patterns, see the samber/cc-skills-golang@golang-error-handling skill.

Subscriptions

Subscriptions use long-lived WebSocket connections. The critical discipline: always respect context cancellation — a leaked goroutine per disconnected client exhausts resources silently.

// ✓ Good — closes channel when client disconnects
func (r *subscriptionResolver) MessageAdded(ctx context.Context, room string) (<-chan *model.Message, error) {
    ch := make(chan *model.Message, 1)
    sub := r.pubsub.Subscribe(room) // subscribe once before the goroutine
    go func() {
        defer close(ch) // always close; signals iteration to stop
        for {
            select {
            case <-ctx.Done():
                return // client disconnected
            case msg := <-sub:
                select {
                case ch <- msg:
                case <-ctx.Done():
                    return
                }
            }
        }
    }()
    return ch, nil
}

// ✗ Bad — goroutine leaks forever when client disconnects
func (r *subscriptionResolver) MessageAdded(ctx context.Context, room string) (<-chan *model.Message, error) {
    ch := make(chan *model.Message, 1)
    go func() {
        for msg := range r.pubsub.Subscribe(room) {
            ch <- msg // blocks forever after client gone
        }
    }()
    return ch, nil
}

Performance and Safety

Production GraphQL servers require explicit limits. Without them, a single deeply nested query exhausts CPU and memory.

// gqlgen — wire these into every production handler
srv := handler.NewDefaultServer(es)
srv.Use(extension.FixedComplexityLimit(200)) // max cost per query

// Gate introspection — only in non-production environments
if os.Getenv("ENV") != "production" {
    srv.Use(extension.Introspection{})
}

For graph-gophers: graphql.MaxDepth(10) and graphql.MaxParallelism(10) options at ParseSchema time.

Query allow-listing: in production, consider persisted queries (gqlgen APQ extension) to reject arbitrary query strings.

Common Mistakes

MistakeWhy it mattersFix
N+1 queries in child resolversOne SQL per parent row → O(n) DB callsUse per-request DataLoader
Global DataLoaderCross-request cache — stale data, data leaksCreate DataLoader in request middleware
Editing models_gen.go directlyNext go generate wipes hand editsUse autobind or models.<T>.model in gqlgen.yml
Forgetting go generate after schema changeResolver interface mismatch at compile timeRe-run go tool gqlgen generate
int field in graph-gophers resolverLibrary requires int32 for Int scalarUse int32 (or float64 for Float)
Introspection enabled in productionExposes full schema to attackersGate with ENV check
No complexity capDeeply nested query → CPU/memory DoSextension.FixedComplexityLimit(N)
Leaking DB errors from resolversExposes SQL internals to clientsWrap in ErrorPresenter / ResolverError
Subscription goroutine leakClient disconnect → goroutine runs foreverdefer close(ch) + select ctx.Done()
Nullable field for always-required dataClients must null-check everywhereMark ! in schema; return error from resolver

Deep Dives

  • gqlgen reference — codegen workflow, gqlgen.yml, DataLoaders, Federation v2, directives

  • graphql-go reference — reflection resolver model, type mapping, tracing

  • Testing — gqlgen client harness, gqltesting, httptest patterns

Cross-References

  • → See samber/cc-skills-golang@golang-context skill for context propagation in resolvers and subscriptions

  • → See samber/cc-skills-golang@golang-error-handling skill for error wrapping and sentinel patterns

  • → See samber/cc-skills-golang@golang-testing skill for table-driven and integration test patterns

  • → See samber/cc-skills-golang@golang-observability skill for tracing and metrics in resolvers

  • → See samber/cc-skills-golang@golang-security skill for input validation and injection prevention

  • → See samber/cc-skills-golang@golang-database skill for N+1 query patterns and DataLoader database batching

References

If you encounter a bug or unexpected behavior in gqlgen, open an issue at https://github.com/99designs/gqlgen/issues.

If you encounter a bug or unexpected behavior in graph-gophers/graphql-go, open an issue at https://github.com/graph-gophers/graphql-go/issues.

Files

evals/evals.json

{
  "skill_name": "golang-graphql",
  "evals": [
    {
      "id": 1,
      "prompt": "I have a gqlgen project with a User type and a Post type. Users have many posts. Write the Go resolver for User.posts. We fetch posts from a PostgreSQL database. The project is set up with a standard gqlgen layout.",
      "expected_output": "A resolver that uses a per-request DataLoader (not direct DB calls) to batch-fetch posts by user IDs. Must NOT query the database directly inside the resolver. Must NOT use a global DataLoader. Should use context to access the per-request loader.",
      "assertions": [
        "Uses a DataLoader or batch loader to fetch posts, not a direct db.Query/QueryContext call inside the resolver method",
        "Accesses the DataLoader from context (not a package-level or global variable)",
        "The resolver function signature uses obj *model.User as a parameter to access the parent user's ID",
        "Does not query the database directly inside the Posts resolver body",
        "Mentions that the DataLoader must be injected per-request via HTTP middleware",
        "DataLoader middleware creates a new loader instance per request, not a shared global"
      ],
      "files": []
    },
    {
      "id": 2,
      "prompt": "We have a graph-gophers/graphql-go project. I need to add a resolver that returns the total comment count for a post. The field is declared as `commentCount: Int!` in the SDL. Write the Go resolver method.",
      "expected_output": "Resolver method using int32 (not int) as the return type for the Int! scalar field. Must use int32, since graph-gophers requires this specific type.",
      "assertions": [
        "Returns int32 (not int, int64, or uint) for the Int! scalar field",
        "Method signature matches the SDL field name (case-insensitive: CommentCount or commentCount)",
        "Does not return plain Go int — which causes a type mismatch at parse time with graph-gophers"
      ],
      "files": []
    },
    {
      "id": 3,
      "prompt": "Set up a production-ready gqlgen HTTP handler. The app will be deployed publicly. We need to make sure it's safe to expose.",
      "expected_output": "Handler setup that gates introspection (disabled or ENV-checked in production) and adds a query complexity limit. Must not leave introspection unconditionally enabled.",
      "assertions": [
        "Introspection is gated — either disabled in production or guarded by an environment variable check",
        "A complexity limit is set using extension.FixedComplexityLimit or equivalent",
        "Does NOT call srv.Use(extension.Introspection{}) unconditionally without an env guard",
        "Uses handler.New or handler.NewDefaultServer from github.com/99designs/gqlgen/graphql/handler",
        "Mentions MaxDepth or complexity limiting as a protection against deeply nested queries"
      ],
      "files": []
    },
    {
      "id": 4,
      "prompt": "Implement a messageAdded subscription resolver in gqlgen. Messages are published via an in-memory pub/sub system. The resolver should stream new messages to subscribers in a given room.",
      "expected_output": "Subscription resolver that closes the channel on context cancellation (defer close(ch) + ctx.Done() in a select). Must handle client disconnect to avoid goroutine leaks.",
      "assertions": [
        "Uses defer close(ch) to close the output channel when done",
        "Uses a select statement with ctx.Done() to detect client disconnection",
        "Returns a receive-only channel (<-chan *model.Message or similar)",
        "Does not use a plain for-range loop without ctx.Done() check — this would cause a goroutine leak on disconnect",
        "The goroutine terminates when ctx is cancelled"
      ],
      "files": []
    },
    {
      "id": 5,
      "prompt": "I'm using gqlgen and want to customize the User type to reuse my existing domain.User struct instead of having gqlgen generate a new one. The domain struct has an Email field. How do I configure this?",
      "expected_output": "Uses autobind or models.<T>.model in gqlgen.yml to map the GraphQL User type to domain.User. Must NOT instruct editing models_gen.go directly.",
      "assertions": [
        "Uses gqlgen.yml configuration (autobind or models.<T>.model) to bind the existing struct",
        "Does NOT suggest editing models_gen.go or generated.go directly",
        "Shows the correct gqlgen.yml syntax for either autobind or models.<T>.model",
        "Mentions that generated files are overwritten on next go generate"
      ],
      "files": []
    },
    {
      "id": 6,
      "prompt": "In a graph-gophers/graphql-go resolver, I need to return a user profile that includes a nullable bio field. The SDL has: bio: String. Write the Go struct field or return type for bio.",
      "expected_output": "Uses *string (pointer to string) for the nullable String field. Non-pointer string would imply non-null in graph-gophers.",
      "assertions": [
        "Uses *string (pointer) for the nullable bio field, not plain string",
        "Explains that non-pointer = non-null and pointer = nullable in graph-gophers type mapping",
        "Does not use sql.NullString or other DB-specific nullable types for the GraphQL resolver layer"
      ],
      "files": []
    },
    {
      "id": 7,
      "prompt": "My gqlgen resolver calls a database function that can return sql.ErrNoRows or other database errors. Write the resolver for GetUser(id: ID!): User! that handles these cases correctly for clients.",
      "expected_output": "Resolver wraps or transforms errors before returning them. Uses ErrorPresenter or gqlerror.Error with extensions code. Must NOT return raw sql.ErrNoRows to the client.",
      "assertions": [
        "Does NOT return raw sql.ErrNoRows or other internal errors directly to the client",
        "Translates sql.ErrNoRows to a GraphQL error with a meaningful message or extension code (e.g. NOT_FOUND)",
        "Uses gqlerror.Error or gqlerror.Errorf to format the client error",
        "Mentions the ErrorPresenter as the right place to centralize error sanitization",
        "Wraps internal errors so they don't expose SQL messages to API consumers"
      ],
      "files": []
    },
    {
      "id": 8,
      "prompt": "Design a GraphQL mutation for creating a user where the email is always required but the bio is optional. The mutation should handle validation errors gracefully without returning HTTP errors.",
      "expected_output": "Uses a mutation envelope payload type with a user field and an errors field. Email is String! (non-null) in input; bio is String (nullable). Errors are returned in the payload, not as GraphQL top-level errors.",
      "assertions": [
        "Input type has email: String! (non-null) for required email",
        "Input type has bio: String (nullable, no !) for optional bio",
        "Mutation returns a payload envelope type with both user and errors fields",
        "Validation errors are returned inside the payload errors field, not as GraphQL top-level errors",
        "The payload errors field uses a non-null list type like [UserError!]! or similar",
        "Does NOT use HTTP 400/422 errors for validation — uses the GraphQL payload pattern"
      ],
      "files": []
    },
    {
      "id": 9,
      "prompt": "Write a gqlgen subscription resolver for order status updates. Use an in-memory pub/sub broker. The resolver should subscribe to a topic named after the order ID and stream status events.",
      "expected_output": "Resolver subscribes to the pub/sub topic ONCE before launching the goroutine, not inside the goroutine loop. The channel is closed when the context is cancelled.",
      "assertions": [
        "Calls the pub/sub Subscribe (or equivalent) method BEFORE the go func() call, not inside the goroutine",
        "Does NOT call Subscribe() inside the for-select loop body (which would create a new subscription per iteration)",
        "Uses defer close(ch) to signal iteration end",
        "Uses select with ctx.Done() to handle client disconnect",
        "The subscription/topic handle is captured in a variable before the goroutine starts"
      ],
      "files": []
    },
    {
      "id": 10,
      "prompt": "In a graph-gophers/graphql-go project, add a search query: `search(query: String!, first: Int, after: ID): [User!]!`. The first and after arguments are optional pagination parameters. Write the Go args struct for this resolver.",
      "expected_output": "Uses *int32 (not *int or int32) for the nullable Int argument 'first', and graphql.ID (or *graphql.ID) for the after argument. Nullable args use pointer types.",
      "assertions": [
        "Uses *int32 (pointer to int32) for the optional 'first: Int' argument — NOT *int or int32",
        "Uses graphql.ID or *graphql.ID for the 'after: ID' argument",
        "Optional arguments are represented as pointers to allow nil (absent) values",
        "Does NOT use plain int or *int for an Int field in graph-gophers"
      ],
      "files": []
    },
    {
      "id": 11,
      "prompt": "Write a dataloadgen batch function for a gqlgen project that fetches all posts for a list of user IDs. Each user can have zero or more posts.",
      "expected_output": "Batch function returns [][]*domain.Post (a slice of post slices, one per user ID), not []*domain.Post. The outer slice length must match the input IDs length.",
      "assertions": [
        "Batch function return type is [][]*domain.Post (2D slice) or equivalent — NOT []*domain.Post",
        "The outer slice has exactly one element per input user ID (same length as the ids parameter)",
        "Handles users with zero posts by including an empty slice (not nil or missing entry)",
        "Does NOT return a flat []*domain.Post that collapses all posts into one slice"
      ],
      "files": []
    },
    {
      "id": 12,
      "prompt": "Add OpenTelemetry tracing to a graph-gophers/graphql-go server. Show the import statement and the ParseSchema call with the tracer configured.",
      "expected_output": "Uses github.com/graph-gophers/graphql-go/trace/otel import and otel.DefaultTracer() — not an external otelgraphql package. Passed as graphql.Tracer() option.",
      "assertions": [
        "Imports github.com/graph-gophers/graphql-go/trace/otel (the bundled tracer package)",
        "Uses otel.DefaultTracer() to construct the tracer — NOT otelgraphql.DefaultTracer() or similar hallucinated package",
        "Passes the tracer as graphql.Tracer(otel.DefaultTracer()) option to MustParseSchema or ParseSchema",
        "Does NOT import an external third-party otelgraphql package that does not exist in graph-gophers"
      ],
      "files": []
    },
    {
      "id": 13,
      "prompt": "We're building a federated GraphQL system with gqlgen. The User service owns the User type and must be resolvable by its id field from other services. What configuration and code changes are needed?",
      "expected_output": "Configures federation.version: 2 in gqlgen.yml, adds @key(fields: 'id') to the User schema type, and implements a FindUserByID entity resolver. Mentions Apollo Router or Cosmo as the gateway.",
      "assertions": [
        "Adds federation block with version: 2 to gqlgen.yml",
        "Adds @key(fields: \"id\") directive to the User type in the SDL schema",
        "Implements or mentions the FindUserByID entity resolver (generated by gqlgen's federation support)",
        "Imports or links the Apollo Federation v2 spec URL in the schema extend block",
        "Does NOT describe a manual federation approach without gqlgen.yml config"
      ],
      "files": []
    }
  ]
}

Requirements and compatibility

Written for: Claude Code, OpenAI Codex

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Declares allowed tools, Claude Code frontmatter

The author says: Designed for Claude Code, Codex or similar harness, and for projects using Golang.

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
samber
Publisher
Samuel Berthe (Community)
Distributed by
Samuel Berthe
Source
samber/cc-skills-golang · skills/golang-graphql · commit bb1d43d
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by samber or Samuel Berthe.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download golang-graphql.zip