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`.
Install with Codex or Claude Copy this prompt, paste it into Codex, Claude, or another assistant, and let it review the skill page and install it for you.
A direct command skips the review prompt. Inspect the source before running it.
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`.
user-invocable
false
license
MIT
compatibility
Designed for Claude Code or similar AI coding agents, and for projects using Golang.
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) โ prefer it 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
Library
Approach
Type safety
Build step
Best for
github.com/99designs/gqlgen
Codegen
Compile-time
go generate
Large schemas, federation, strict types
github.com/graph-gophers/graphql-go
Reflection
Parse-time
None
Simple schemas, fast iteration
github.com/graphql-go/graphql
Code-first
Runtime
None
Avoid โ 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.
# โ Good โ explicit nullability; ID scalar for opaque identifierstype User {id: ID!email: String!# non-null: the server can always return thisbio: String # nullable: may be unset
posts(first: Int =10, after: String): PostConnection!}# โ Bad โ Int ID leaks implementation details, breaks client cachingtype 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 layerfunc(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 {
returnnil, formatError(err)
}
return &model.CreateUserPayload{User: toGQLUser(user)}, nil
}
// โ Bad โ SQL in resolver, no separation of concernsfunc(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 middlewarefuncDataLoaderMiddleware(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 requestsvar 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:
HTTP middleware โ extract and validate tokens, stash identity in context.Context.
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.
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 disconnectsfunc(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 goroutinegofunc() {
deferclose(ch) // always close; signals iteration to stopfor {
select {
case <-ctx.Done():
return// client disconnectedcase msg := <-sub:
select {
case ch <- msg:
case <-ctx.Done():
return
}
}
}
}()
return ch, nil
}
// โ Bad โ goroutine leaks forever when client disconnectsfunc(r *subscriptionResolver) MessageAdded(ctx context.Context, room string) (<-chan *model.Message, error) {
ch := make(chan *model.Message, 1)
gofunc() {
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 environmentsif 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.