Introduction
gqlgen generates Go code from GraphQL schemas, producing type-safe resolvers, models, and a runtime that handles query parsing, validation, and execution. You write the schema in standard GraphQL SDL, run the generator, and fill in resolver stubs with your business logic.
What gqlgen Does
- Generates type-safe Go structs and resolver interfaces from GraphQL SDL
- Handles query parsing, validation, and execution at runtime
- Supports subscriptions over WebSocket out of the box
- Provides dataloading patterns to solve the N+1 query problem
- Integrates with any HTTP router via a standard http.Handler
Architecture Overview
gqlgen reads .graphql schema files and a gqlgen.yml config, then generates Go types for every object, input, and enum plus an interface for each resolver. At runtime, the generated execution engine walks the parsed query AST, calls your resolver methods, and assembles the JSON response. Complexity limiting and tracing middleware are built into the execution pipeline.
Setup & Configuration
- Initialize a project with
go run github.com/99designs/gqlgen init - Define your schema in
graph/schema.graphqls - Customize model binding and paths in
gqlgen.yml - Regenerate after schema changes with
go run github.com/99designs/gqlgen generate - Mount the handler:
srv := handler.NewDefaultServer(graph.NewExecutableSchema(...))
Key Features
- Schema-first development with automatic code generation
- Supports federation for distributed GraphQL architectures
- Built-in query complexity analysis to prevent abusive queries
- Plugin system for custom directives, validation, and middleware
- File upload support via the GraphQL multipart request spec
Comparison with Similar Tools
- graphql-go — runtime-only library without code generation; resolvers use
interface{}instead of typed arguments - Apollo Server (Node.js) — ecosystem leader in JavaScript; gqlgen offers comparable features in Go with compiled performance
- Hasura — auto-generates GraphQL APIs from a database; gqlgen gives full control over resolver logic
- Juniper (Rust) — similar code-gen approach for Rust; gqlgen targets Go with its own plugin model
FAQ
Q: Can I use gqlgen with an existing Go project?
A: Yes. Run gqlgen init in a subdirectory, point gqlgen.yml at your existing models, and mount the handler on your router.
Q: How does gqlgen handle N+1 queries? A: gqlgen documents a dataloader pattern using middleware to batch and cache database calls within a single request.
Q: Does gqlgen support Apollo Federation?
A: Yes. Enable federation in gqlgen.yml and add the @key directive to your schema entities.
Q: What Go version is required? A: gqlgen requires Go 1.20 or later.