Golang Graphql
Samuel BertheCommunityCreated by samberDistributed by Samuel Berthe
- Skill
- Tool integration
- Software development
- MIT
- No issues found
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
Download the skill as a ZIP:
https://autogineer.com/agent-skills/samber/golang-graphql/downloadUnzip 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-graphqlskill 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-devskill (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-goplsskill (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.
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:
HTTP middleware — extract and validate tokens, stash identity in
context.Context.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
| Mistake | Why it matters | Fix |
|---|---|---|
| N+1 queries in child resolvers | One SQL per parent row → O(n) DB calls | Use per-request DataLoader |
| Global DataLoader | Cross-request cache — stale data, data leaks | Create DataLoader in request middleware |
Editing models_gen.go directly | Next go generate wipes hand edits | Use autobind or models.<T>.model in gqlgen.yml |
Forgetting go generate after schema change | Resolver interface mismatch at compile time | Re-run go tool gqlgen generate |
int field in graph-gophers resolver | Library requires int32 for Int scalar | Use int32 (or float64 for Float) |
| Introspection enabled in production | Exposes full schema to attackers | Gate with ENV check |
| No complexity cap | Deeply nested query → CPU/memory DoS | extension.FixedComplexityLimit(N) |
| Leaking DB errors from resolvers | Exposes SQL internals to clients | Wrap in ErrorPresenter / ResolverError |
| Subscription goroutine leak | Client disconnect → goroutine runs forever | defer close(ch) + select ctx.Done() |
| Nullable field for always-required data | Clients must null-check everywhere | Mark ! in schema; return error from resolver |
Deep Dives
gqlgen reference — codegen workflow,
gqlgen.yml, DataLoaders, Federation v2, directivesgraphql-go reference — reflection resolver model, type mapping, tracing
Testing — gqlgen client harness, gqltesting, httptest patterns
Cross-References
→ See
samber/cc-skills-golang@golang-contextskill for context propagation in resolvers and subscriptions→ See
samber/cc-skills-golang@golang-error-handlingskill for error wrapping and sentinel patterns→ See
samber/cc-skills-golang@golang-testingskill for table-driven and integration test patterns→ See
samber/cc-skills-golang@golang-observabilityskill for tracing and metrics in resolvers→ See
samber/cc-skills-golang@golang-securityskill for input validation and injection prevention→ See
samber/cc-skills-golang@golang-databaseskill 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
- ATTRIBUTION.mdAdded by AutoGineer899 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md12.8 KiB
- evals/evals.json11.5 KiB
- references/gqlgen.md7.8 KiB
- references/graphql-go.md7.6 KiB
- references/testing.md5.3 KiB
references/gqlgen.md
gqlgen Reference
gqlgen is a schema-first, code-generation library. Write SDL, run go generate, fill in resolver bodies.
Table of Contents
Project Setup
gqlgen.yml
Resolver Structure
DataLoaders (gqlgen)
Authentication Directives
Middleware Hooks
Error Presenter
Subscriptions
File Uploads
Apollo Federation v2
Production Handler Setup
Project Setup
# Bootstrap a new project
go run github.com/99designs/gqlgen init
# Pin the tool in go.mod for reproducible generation (Go 1.24+)
go get -tool github.com/99designs/gqlgen@latestFor Go <1.24 modules, use the legacy tools.go blank-import workaround instead.
# Regenerate after every schema change
go tool gqlgen generateNever hand-edit generated files (generated.go, models_gen.go) — generate overwrites them.
gqlgen.yml
schema:
- graph/schema/*.graphql
exec:
filename: graph/generated.go
package: graph
model:
filename: graph/model/models_gen.go
package: model
resolver:
layout: follow-schema # one resolvers file per schema file
dir: graph
package: graph
filename_template: "{name}.resolvers.go"
autobind:
- github.com/me/app/internal/domain # reuse existing structs
models:
# ID: graphql.IntID # legacy only — use opaque string IDs for new schemas
User:
model: github.com/me/app/internal/domain.User
fields:
posts:
resolver: true # force a custom resolver (required for DataLoader fields)
omit_slice_element_pointers: true
struct_fields_always_pointers: false
resolvers_always_return_pointers: trueKey knobs:
autobind— maps Go structs to GraphQL types; fields must match by name (case-insensitive)models.<T>.model— override which Go type backs a GraphQL typefields.<f>.resolver: true— force a custom resolver instead of struct field access; required for any field that should batch via DataLoaderstruct_fields_always_pointers/resolvers_always_return_pointers— controls*TvsTin generated signatures; match your domain model conventions
Resolver Structure
The generated Config holds a Resolvers field of the generated interface. You implement it:
// graph/resolver.go — you own this file, not generated
type Resolver struct {
db *sql.DB
userService *service.UserService
loaders *dataloaders.Loaders // injected per-request
}Per-type resolvers implement the generated interface split by GraphQL type:
type queryResolver struct{ *Resolver }
type mutationResolver struct{ *Resolver }
type userResolver struct{ *Resolver }
func (r *queryResolver) User(ctx context.Context, id string) (*model.User, error) { ... }
func (r *userResolver) Posts(ctx context.Context, obj *model.User) ([]*model.Post, error) { ... }obj is the parent object — the entry point for walking the graph.
DataLoaders (gqlgen)
Use github.com/vikstrous/dataloadgen (generics, fast) or github.com/graph-gophers/dataloader:
// Inject per-request via middleware
func Middleware(db *sql.DB, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
loaders := &Loaders{
PostsByUserID: dataloadgen.NewLoader(func(ctx context.Context, ids []string) ([][]*domain.Post, []error) {
return batchPostsByUserID(ctx, db, ids) // returns one []Post per user ID
}, dataloadgen.WithWait(1*time.Millisecond)),
}
ctx := context.WithValue(r.Context(), loadersKey, loaders)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// Resolver uses the loader — never the DB directly
func (r *userResolver) Posts(ctx context.Context, obj *model.User) ([]*model.Post, error) {
return loaders.For(ctx).PostsByUserID.Load(ctx, obj.ID)
}Set wait to 1–2ms — allows multiple concurrent resolvers to register keys before the batch fires.
Authentication Directives
directive @hasRole(role: Role!) on FIELD_DEFINITION
type Query {
adminStats: Stats! @hasRole(role: ADMIN)
}// Implement the directive function
func HasRole(ctx context.Context, obj any, next graphql.Resolver, role model.Role) (any, error) {
user := auth.UserFromContext(ctx)
if user == nil || user.Role != role {
return nil, &gqlerror.Error{
Message: "access denied",
Extensions: map[string]any{"code": "FORBIDDEN"},
}
}
return next(ctx)
}
// Register at server bootstrap
c := generated.Config{
Resolvers: &graph.Resolver{...},
Directives: generated.DirectiveRoot{
HasRole: HasRole,
},
}Middleware Hooks
srv.AroundOperations(func(ctx context.Context, next graphql.OperationHandler) graphql.ResponseHandler {
// log operation name, add trace span
return next(ctx)
})
srv.AroundFields(func(ctx context.Context, next graphql.Resolver) (any, error) {
// per-field tracing, timing
return next(ctx)
})Error Presenter
srv.SetErrorPresenter(func(ctx context.Context, err error) *gqlerror.Error {
var gqlErr *gqlerror.Error
if errors.As(err, &gqlErr) {
return gqlErr
}
log.Ctx(ctx).Error("resolver error", "err", err)
return gqlerror.Errorf("internal server error")
})
srv.SetRecoverFunc(func(ctx context.Context, err any) error {
log.Ctx(ctx).Error("panic in resolver", "err", err)
return fmt.Errorf("internal server error")
})Subscriptions
srv.AddTransport(transport.Websocket{
KeepAlivePingInterval: 10 * time.Second,
Upgrader: websocket.Upgrader{
// Restrict to your own origin in production; true here is dev-only.
CheckOrigin: func(r *http.Request) bool {
return r.Header.Get("Origin") == "https://app.example.com"
},
},
InitFunc: func(ctx context.Context, initPayload transport.InitPayload) (context.Context, *transport.InitPayload, error) {
// auth at connection time
token := initPayload.Authorization()
user, err := validateToken(token)
if err != nil {
return ctx, nil, err
}
return context.WithValue(ctx, userKey, user), &initPayload, nil
},
})gqlgen supports both graphql-ws (legacy) and graphql-transport-ws (current) subprotocols.
File Uploads
srv.AddTransport(transport.MultipartForm{
MaxUploadSize: 10 << 20, // 10 MB total
MaxMemory: 5 << 20, // 5 MB in memory; rest spills to disk
})Schema:
scalar Upload
type Mutation {
uploadAvatar(file: Upload!): User!
}Resolver receives graphql.Upload{File io.Reader, Filename string, Size int64, ContentType string}.
Apollo Federation v2
gqlgen.yml:
federation:
filename: graph/federation.go
version: 2Schema:
extend schema
@link(
url: "https://specs.apollo.dev/federation/v2.3"
import: ["@key", "@shareable", "@external"]
)
type User @key(fields: "id") {
id: ID!
name: String!
}Implement FindUserByID in the generated entity resolver. Works with Apollo Router and Cosmo.
Production Handler Setup
srv := handler.New(es)
srv.AddTransport(transport.Options{})
srv.AddTransport(transport.GET{})
srv.AddTransport(transport.POST{})
srv.AddTransport(transport.MultipartForm{MaxUploadSize: 10 << 20, MaxMemory: 5 << 20})
srv.AddTransport(transport.Websocket{KeepAlivePingInterval: 10 * time.Second})
srv.SetQueryCache(lru.New[*ast.QueryDocument](1000))
if os.Getenv("ENV") != "production" {
srv.Use(extension.Introspection{})
}
srv.Use(extension.AutomaticPersistedQuery{Cache: lru.New[string](100)})
srv.Use(extension.FixedComplexityLimit(200))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