GraphQL in Go with gqlgen: Schema, Resolvers, DI, Testing
"GraphQL is a query language designed to build client applications by providing an intuitive and flexible syntax and system for describing their data requirements and interactions." — GraphQL Specification, October 2021 edition, Introduction
Summary: GraphQL gives clients one typed endpoint where they ask for exactly the fields they need; in Go, gqlgen turns your SDL schema into an executable schema plus resolver stubs, and the real work is everything around that: injecting services into the Resolver, batching with dataloaders, bounding what a client may ask for, mapping errors, paginating with cursors, and testing it all in process. Focus: GraphQL schema (SDL: types, queries, mutations, subscriptions, inputs, enums, interfaces, unions, scalars, non-null, lists), gqlgen (gqlgen.yml, autobind, models, generate, resolvers, resolver stubs), schema-first vs code-first (graph-gophers/graphql-go, 99designs/gqlgen vs graphql-go/graphql), resolver DI (Resolver struct with services), context in resolvers, dataloaders (N+1, graph-gophers/dataloader, vikstrous/dataloadgen), field-level resolvers, custom scalars (Time, UUID), directives (@goField, custom auth directive), error handling (gqlerror, extensions, partial responses), pagination (Relay cursor connections), subscriptions over WebSockets (gorilla/websocket transport), query complexity limits, depth limiting, introspection in production, persisted queries (APQ), batching, tracing (OpenTelemetry), testing with client.New / httptest, GraphQL playground, Federation pointer, REST vs GraphQL vs gRPC trade-offs, Laravel Lighthouse comparison. Learning goal: Stand up a GraphQL API in Go that you can defend in a review: a schema you can read, resolvers that receive their services by injection, no N+1, bounded query cost, errors the client can act on, and tests that run the whole stack without a network.
This page owns GraphQL as a server technology in Go. It does not re-teach its neighbours: the protocol-neutral concepts (schema, resolvers, why N+1 happens, when GraphQL wins) are in GraphQL: Schema, Resolvers, N+1, When It Wins and the REST-versus-GraphQL contract design in API Realization: REST, API Management, GraphQL and REST API Design; the HTTP server, ServeMux and middleware are in net/http and Middlewares; a layered REST service is in A REST API in Go; database/sql and pgx are in database/sql & pgx; cancellation and deadlines are in context; the binary RPC alternative is in gRPC & Protobuf in Go; password hashing, sessions and JWT are in Authentication in Go; test layout and httptest are in Testing & Benchmarking and interface fakes in Mocking with Interfaces & DI.
Facts below were checked against the GraphQL specification (October 2021 edition and the current draft), the GraphQL over HTTP draft, the gqlgen documentation site and the gqlgen v0.17.86 source (the code in this chapter is pinned to that tag), the vikstrous/dataloadgen and graph-gophers/dataloader READMEs, the Relay cursor connections specification, the OWASP GraphQL cheat sheet, the Lighthouse (Laravel) documentation and the Go 1.21, 1.22 and 1.24 release notes. pkg.go.dev returns 403 to scripted fetches, so package facts come from the source at the tag and from go.dev. The snippets declare go 1.24 and were compiled, vetted and tested with -race on Go 1.27.4 (macOS). One caveat is load-bearing and explained in the codegen block: the generated code is committed so go test needs no code generation, but regenerating it with the pinned gqlgen on Go 1.27.4 fails, so the regeneration command in this chapter selects a Go 1.24 toolchain.
Page map
| If you are looking for | Go to |
|---|---|
| The tables you can memorise in one minute | Everything in one minute |
| Why a client-shaped query language exists | Why it exists |
| Where GraphQL and gqlgen come from, and which Go libraries exist | Where it comes from |
| A resolver that causes N+1, and the fix | Go |
| Types, queries, mutations, subscriptions, inputs, enums, interfaces, unions, scalars, non-null, lists | The schema in SDL |
| What the server does with a query; mutations run serially | Operations and execution |
gqlgen.yml, autobind, models, generate, resolver stubs | gqlgen: config and codegen |
| graph-gophers/graphql-go, graphql-go/graphql, thunder | Schema-first vs code-first |
The Resolver struct and injecting services | Resolver DI |
ctx inside a resolver | Context in resolvers |
@goField(forceResolver: true), Book.author | Field-level resolvers |
N+1, vikstrous/dataloadgen, graph-gophers/dataloader | Dataloaders |
Time, UUID, MarshalUUID | Custom scalars |
@auth, DirectiveRoot, @goField | Directives |
| Authentication versus authorization, where each lives | Authentication and authorization |
gqlerror, extensions.code, partial responses | Errors |
Relay connections, edges, pageInfo, cursors | Pagination |
subscription, transport.Websocket, gorilla | Subscriptions |
| Complexity and depth limits | Complexity and depth limits |
| Introspection and the playground in production | Introspection and the playground |
| Automatic persisted queries, persisted-query allow-lists | Persisted queries (APQ) |
| Request batching, alias batching | Batching |
| OpenTelemetry spans per operation and field | Tracing |
client.New, httptest, asserting query counts | Testing |
| Status codes, GET versus POST, caching, CORS | HTTP details |
| Apollo Federation, schema stitching | Federation pointer |
| Exact messages and extension codes | Mechanics |
| The common bugs and their fixes | Solving the classic problems |
| REST vs GraphQL vs gRPC | Choosing |
| Monolith to many services | In architecture |
| Reproduce it on your machine | Lab |
| Lighthouse, Laravel | For PHP/Laravel developers |
Everything in one minute
The building blocks. Each row is unpacked in the concept catalogue.
| Block | What it is | Plain words | In this chapter's code |
|---|---|---|---|
| SDL | Schema Definition Language | The contract: every type, field, argument and its nullability | graph/schema.graphql |
| Operation | query, mutation, subscription | One request: read, write, or a stream of events | Query, Mutation, Subscription types |
| Resolver | Function that produces one field's value | "How do I get this field?" | graph/schema.resolvers.go |
| Resolver struct | Root object all resolvers hang off | Where the injected services live | graph.Resolver |
| Dataloader | Per-request batch-and-cache | "Collect many lookups, ask once" | loaders.Loaders |
| Directive | Annotation with behaviour | Reusable field middleware | @auth, @goField |
| Scalar | Leaf type with custom wire format | A value that is not an object | Time, UUID |
| Connection | Relay pagination shape | A page of edges with cursors | BookConnection |
| Extension | gqlgen handler middleware | Limits, APQ, tracing, introspection | server.New |
| Transport | How bytes reach the server | POST, GET, WebSocket | transport.POST, transport.Websocket |
The keyword map. Everything a practitioner meets, in the order this page unpacks it; the right column says where.
| Topic (as practitioners say it) | Where on this page |
|---|---|
| GraphQL schema (SDL: types, queries, mutations, subscriptions, inputs, enums, interfaces, unions, scalars, non-null, lists) | The schema in SDL |
| gqlgen (gqlgen.yml, autobind, models, generate, resolvers, resolver stubs) | gqlgen |
| schema-first vs code-first (graph-gophers/graphql-go, 99designs/gqlgen vs graphql-go/graphql) | Schema-first vs code-first |
| resolver DI (Resolver struct with services) | Resolver DI |
| context in resolvers | Context in resolvers |
| dataloaders (N+1, graph-gophers/dataloader, vikstrous/dataloadgen) | Dataloaders |
| field-level resolvers | Field-level resolvers |
| custom scalars (Time, UUID) | Custom scalars |
| directives (@goField, custom auth directive) | Directives |
| error handling (gqlerror, extensions, partial responses) | Errors |
| pagination (Relay cursor connections) | Pagination |
| subscriptions over WebSockets (gorilla/websocket transport) | Subscriptions |
| query complexity limits, depth limiting | Limits |
| introspection in production, GraphQL playground | Introspection |
| persisted queries (APQ) | APQ |
| batching | Batching |
| tracing (OpenTelemetry) | Tracing |
| testing with client.New / httptest | Testing |
| Federation pointer | Federation |
| REST vs GraphQL vs gRPC trade-offs | Choosing |
| Laravel Lighthouse comparison | For PHP/Laravel developers |
What a response looks like. The shape never changes: data mirrors the query, errors (only if something went wrong) lists problems with a path and optional extensions, and both may be present at once.
| Situation | HTTP status (gqlgen) | data | errors |
|---|---|---|---|
| All good | 200 | filled | absent |
| A nullable field's resolver failed | 200 | that field null, rest filled | one entry with path |
| A non-null field failed | 200 | nearest nullable parent null | one entry with path |
| Query does not parse or validate | 422 (measured, gqlgen v0.17.86, no Accept); 400 with application/graphql-response+json | absent | entries with locations, no path |
| Complexity or depth limit exceeded | 200 (measured; the extension runs after validation) | absent | extensions.code set |
| Persisted hash not yet registered | 200 (measured) | absent | PersistedQueryNotFound |
| Body is not JSON | 400 (measured) | absent | one entry |
The protections a public endpoint needs, cheapest first (picture in the Mechanics section):
| Layer | Stops | Where |
|---|---|---|
| Body size, header timeout, rate limit | Floods, slowloris | http.Server, Middlewares |
| Persisted-query allow-list | Arbitrary queries | APQ is only a cache; an allow-list refuses unknown hashes |
| Introspection off, suggestions off | Schema reconnaissance | extension.Introspection absent; SetDisableSuggestion |
| Depth limit | Deeply nested cycles | limits.Depth |
| Complexity limit | Wide and multiplied lists | extension.FixedComplexityLimit |
| Timeouts | Slow resolvers | ctx deadline, context |
| Authorization | Reading what you may not | Directive plus service layer |
Why it exists
A REST endpoint returns what its author decided to return. A mobile screen that needs a book's title, its author's name and the author's three latest books either makes three requests (under-fetching, and each one waits for the previous) or calls a purpose-built endpoint that someone has to write, version and keep. A web page that needs only the title downloads the whole book (over-fetching). Multiply by five clients and three teams and the backend becomes a queue of "can you add a field to that endpoint".
GraphQL moves the choice to the client without giving up types: the server publishes a schema, the client sends a query naming the fields it wants, the server returns exactly that shape. One endpoint, one round trip, a contract both sides can generate code from. The price is real: the server must now defend itself against queries it has never seen, caching by URL stops working, and a naive implementation issues one database query per list item.
| Weaker, simpler (REST resources) | Stronger, richer (GraphQL) |
|---|---|
| Server fixes each response shape | Client picks the fields |
| Many URLs, HTTP caching works | One URL, caching needs ids or persisted queries |
| Cost of a request is predictable | Cost depends on the query; needs limits |
| Versioning by URL or header | Evolution by adding fields and @deprecated |
| Errors are HTTP status codes | Errors are data: HTTP 200 with an errors array |
Trivial to test with curl | Needs a query, or a client library |
An everyday picture. A restaurant with a fixed menu (REST: set meals) versus a buffet where you point at what you want and the kitchen plates exactly that (GraphQL). The buffet is great for fussy diners, but the kitchen needs a rule against someone ordering forty dishes at once, a waiter who fetches all the tomatoes in one trip rather than one tomato per dish (the dataloader), and a menu board outside, which you may not want strangers to read in full (introspection).
Three common misunderstandings, up front
- "GraphQL is a database query language." It is an API contract and execution model. Your resolvers can read SQL, call gRPC, hit a cache or return constants.
- "GraphQL solves over-fetching, so it is faster." It removes wasted bytes on the wire; the server work is the same or higher unless you batch. Without a dataloader, a nested query is slower than the REST endpoint it replaced.
- "One endpoint means no HTTP semantics to worry about." Status codes, caching, CORS, authentication, timeouts and rate limiting are all still yours; they just move from the router into a single handler and a few extensions.
Where it comes from
The specification says GraphQL is "originally created at Facebook in 2012", that "the development of this open standard started in 2015", that it was licensed under OWFa 1.0 in 2017, and that "The GraphQL Foundation was formed in 2019". The October 2021 edition is the one graph-gophers/graphql-go says it targets; the working draft on spec.graphql.org mentions oneOf input objects, which the 2021 text does not, and libraries adopt draft features at their own pace. Two sibling documents matter in Go: the GraphQL over HTTP draft (media type application/graphql-response+json, status code rules) and the Relay cursor connections specification (the pagination shape every client library expects).
On the Go side, three code generators and libraries appeared in the 2016-2018 window and still define the choices. graphql-go/graphql (a port of the JavaScript reference implementation) builds types at run time. graph-gophers/graphql-go parses SDL and matches resolvers by method sets. 99designs/gqlgen generates an executable schema from SDL and binds it to your Go types. gqlgen's own comparison page labels itself "schema first", graph-gophers "schema first", graphql-go/graphql "run time types" and thunder "struct first". gqlgen is the one this chapter uses because it generates type-safe code, which its README states as a principle: "You should never see map[string]interface{} here."
| Version / date | What changed | Why it matters here |
|---|---|---|
| 2012 | Created at Facebook | Per the spec foreword |
| 2015 | Open standard development begins | Spec, reference implementation |
| 2019 | GraphQL Foundation formed | Neutral home for the spec |
| 2021-10 | Spec October 2021 edition | Target of graph-gophers/graphql-go |
| gqlgen v0.17.80 and v0.17.86 (checked) | go.mod says go 1.24.0; WebSocket transport on gorilla/websocket | v0.17.86 is the newest go 1.24 one: v0.17.87 already says go 1.25 |
| gqlgen v0.17.88 and v0.17.90 (checked) | go 1.25; still gorilla | Needs a newer module go line |
| gqlgen v0.17.91 | go.mod lists both coder/websocket and gorilla/websocket | Transition release |
| gqlgen v0.17.92 (checked) | go.mod lists only coder/websocket | The gorilla Upgrader in this chapter is version-specific |
| gqlgen v0.17.96 and v0.17.98 (checked) | go 1.26.0 | Latest at time of writing is v0.17.98 |
| Go 1.24 | tool directive in go.mod, go get -tool | gqlgen is pinned as a tool dependency, no tools.go |
The module in this chapter pins v0.17.86 deliberately: it is the newest release whose own go.mod says go 1.24 (v0.17.87 says go 1.25; the go.mod of each checked tag is saved in the sources folder), matching the repository's snippet rule. Everything about the WebSocket upgrader below is true of that tag; on v0.17.92 and later the transport is configured against coder/websocket, so check the release notes before upgrading.
Go
Before
The classic bug, in its smallest form: a list query, then one author query per book. Nothing is wrong in any single function, which is why it ships.
// Package before shows the classic resolver bug in its smallest form: one
// query for the list, then one more per item. A GraphQL server hits this the
// moment a list field has a resolver that talks to the database.
package before
import (
"context"
"academy/graphql-in-go/graph/model"
)
// Store is the slice of the data layer the "resolvers" need.
type Store interface {
BooksPage(ctx context.Context, authorID, afterID string, first int) ([]*model.Book, bool, int, error)
AuthorByID(ctx context.Context, id string) (*model.Author, error)
}
// Row is what the client asked for: a title and the author's name.
type Row struct{ Title, Author string }
// BooksWithAuthors is what `{ books { edges { node { title author { name } } } } }`
// costs when Book.author is resolved item by item: 1 + N queries.
func BooksWithAuthors(ctx context.Context, s Store, n int) ([]Row, error) {
books, _, _, err := s.BooksPage(ctx, "", "", n) // 1 query
if err != nil {
return nil, err
}
rows := make([]Row, 0, len(books))
for _, b := range books {
a, err := s.AuthorByID(ctx, b.AuthorID) // N queries, one per book
if err != nil {
return nil, err
}
rows = append(rows, Row{Title: b.Title, Author: a.Name})
}
return rows, nil
}The test proves the cost: six books cost one list query plus six author queries.
package before
import (
"context"
"testing"
"academy/graphql-in-go/store"
)
func TestNPlusOne(t *testing.T) {
db := store.NewMemory()
rows, err := BooksWithAuthors(context.Background(), db, 6)
if err != nil {
t.Fatal(err)
}
if len(rows) != 6 {
t.Fatalf("rows = %d, want 6", len(rows))
}
st := db.Stats()
// 6 books -> 1 list query + 6 author queries.
if st.BookQueries != 1 || st.AuthorQueries != 6 {
t.Fatalf("stats = %+v, want 1 book query and 6 author queries", st)
}
}After
The same result with a dataloader: every item asks the per-request loader for its author, the loader waits about two milliseconds, collects the distinct keys and sends one batched query.
// Package after fixes the N+1 with a dataloader: every item asks the loader
// for its author, the loader waits a few milliseconds, collects the keys and
// sends ONE batched query. gqlgen runs list-item field resolvers in
// goroutines, which is exactly what makes the batching window fill up.
package after
import (
"context"
"sync"
"time"
"academy/graphql-in-go/graph/model"
"academy/graphql-in-go/loaders"
)
// Store adds the batched author query to what `before` used.
type Store interface {
BooksPage(ctx context.Context, authorID, afterID string, first int) ([]*model.Book, bool, int, error)
AuthorsByIDs(ctx context.Context, ids []string) ([]*model.Author, error)
}
// Row is what the client asked for.
type Row struct{ Title, Author string }
// BooksWithAuthors costs 1 + 1 queries however many books there are.
func BooksWithAuthors(ctx context.Context, s Store, n int) ([]Row, error) {
books, _, _, err := s.BooksPage(ctx, "", "", n) // 1 query
if err != nil {
return nil, err
}
l := loaders.New(s, 2*time.Millisecond) // one loader per request
rows := make([]Row, len(books))
errs := make([]error, len(books))
var wg sync.WaitGroup
for i, b := range books { // what gqlgen does for a list of objects
wg.Add(1)
go func() {
defer wg.Done()
a, err := l.Author.Load(ctx, b.AuthorID) // joins the open batch
if err != nil {
errs[i] = err
return
}
rows[i] = Row{Title: b.Title, Author: a.Name}
}()
}
wg.Wait()
for _, err := range errs {
if err != nil {
return nil, err
}
}
return rows, nil
}package after
import (
"context"
"testing"
"academy/graphql-in-go/store"
)
func TestBatched(t *testing.T) {
db := store.NewMemory()
rows, err := BooksWithAuthors(context.Background(), db, 6)
if err != nil {
t.Fatal(err)
}
if len(rows) != 6 || rows[0].Author == "" {
t.Fatalf("rows = %+v", rows)
}
st := db.Stats()
if st.BookQueries != 1 || st.AuthorQueries != 1 {
t.Fatalf("stats = %+v, want 1 book query and 1 batched author query", st)
}
}The Go angle
Go's concurrency model is why the dataloader works so well here: gqlgen runs the field resolvers of a list's items in separate goroutines, so by the time the first Load call arrives, its siblings are only microseconds behind and the batching window fills. In a single-threaded runtime the same pattern needs tick scheduling tricks. Two language details are in play: the after snippet starts one goroutine per item and captures the loop variables i and b directly, which is correct only since Go 1.22 gave each iteration its own variables, and limits.Depth uses the max built-in added in Go 1.21. The cost of that concurrency is that every resolver and every service must be safe for concurrent use (see Race Conditions), and that ctx must flow through every call so a cancelled request stops all those goroutines (context).
The second Go-specific point is that gqlgen is a code generator, not a framework with reflection at request time. The executable schema is ordinary Go in generated.go (5,028 lines for this tiny schema), checked into version control, type-checked by the compiler, and visible in a debugger. That is why the chapter's snippet module can commit it and why go test needs no generation step.
The concept catalogue
The schema in SDL Must-know
In plain words: The schema is the menu: a list of every type the API exposes, every field on those types, what arguments a field takes, and whether it can be null. Clients read the menu, servers promise to serve it.
Common misunderstanding: "The schema describes my database tables." It describes the API a client sees. Book.author is a field you resolve however you like; there is no foreign key in the SDL, and a type can combine data from three services.
Definition: The Schema Definition Language declares object types (type Book { ... }), the three root operation types Query, Mutation and Subscription, input types for arguments (input NewBook), enums, interfaces (shared fields, interface Node { id: ID! }), unions (union SearchResult = Author | Book), scalars (Int, Float, String, Boolean, ID plus custom ones) and directives. ! means non-null and [T!]! is a non-null list of non-null items. The spec's rule for nullability is the one that shapes error handling: when a non-null field fails, "the field error is further propagated to its parent field" until a nullable parent can become null.
SDL piece Reads as
String nullable string
String! string, never null
[Book!]! list never null, items never null
[Book] list may be null, items may be null
books(first: Int = 10): BookConnection!
field with an argument and a default
union SearchResult = Author | Book
one of these object types; query with "... on Author"Real scenario: a catalogue where Book.rating is nullable because the ratings service is flaky (the page still renders), while Book.title is non-null because a book without a title is a data bug; a search field that returns authors and books mixed; an addBook(input: NewBook!) mutation whose input type is reused by an updateBook.
| SDL construct | Go (gqlgen) | Notes |
|---|---|---|
type Book | struct, generated or autobound | Fields with arguments or forceResolver become resolver methods |
input NewBook | struct passed by value | Generated into models_gen.go |
enum Role | type Role string with constants | Generated, or bound to yours (here model.Role) |
interface Node | Go interface Node | Types implement the marker method IsNode() |
union SearchResult | Go interface with IsSearchResult() | Resolver returns []model.SearchResult |
scalar Time | time.Time via graphql.Time | See Custom scalars |
String! / String | string / *string | Nullable becomes a pointer |
[Book!]! | []*model.Book | Items are pointers for objects |
The whole schema of this chapter, 75 lines, is the contract the rest of the page implements.
# A small library catalogue: enough SDL to show every building block.
"RFC 3339 timestamp (gqlgen's built-in graphql.Time)."
scalar Time
"RFC 4122 UUID in its canonical text form."
scalar UUID
directive @goField(forceResolver: Boolean, name: String) on INPUT_FIELD_DEFINITION | FIELD_DEFINITION
directive @auth(role: Role!) on FIELD_DEFINITION
enum Role {
READER
EDITOR
ADMIN
}
interface Node {
id: ID!
}
type Author implements Node {
id: ID!
name: String!
"Field-level resolver: books are loaded only when the client asks for them."
books(first: Int = 10, after: String): BookConnection! @goField(forceResolver: true)
}
type Book implements Node {
id: ID!
externalId: UUID!
title: String!
publishedAt: Time!
tags: [String!]!
author: Author! @goField(forceResolver: true)
"Nullable on purpose: a failing resolver yields null plus an entry in errors."
rating: Float @goField(forceResolver: true)
}
union SearchResult = Author | Book
"All four fields are required by the Relay connections spec."
type PageInfo {
hasNextPage: Boolean!
hasPreviousPage: Boolean!
startCursor: String
endCursor: String
}
type BookEdge {
cursor: String!
node: Book!
}
type BookConnection {
edges: [BookEdge!]!
pageInfo: PageInfo!
totalCount: Int!
}
input NewBook {
title: String!
authorId: ID!
tags: [String!]
}
type Query {
book(id: ID!): Book
books(first: Int = 10, after: String): BookConnection!
search(term: String!): [SearchResult!]!
"Needs any signed-in role; see the @auth directive."
secretShelf: [Book!]! @auth(role: READER)
}
type Mutation {
addBook(input: NewBook!): Book! @auth(role: EDITOR)
}
type Subscription {
bookAdded: Book!
}Fix / how to use it: design nullability on purpose. Make a field nullable if its resolver can fail independently and the client can live without it; make it non-null if a missing value is a bug. Prefer inputs over long argument lists, and ID! over Int! for identifiers (IDs are opaque strings on the wire).
Operations and execution Must-know
In plain words: A request carries one operation. A query reads, a mutation writes, a subscription stays open and streams. The server runs the top-level fields of a query in any order, possibly in parallel, but runs a mutation's top-level fields one after another.
Common misunderstanding: "A query may change data as long as I document it." The spec forbids it: "the resolution of fields other than top-level mutation fields must always be side effect-free and idempotent", which is exactly why the executor may run them in any order, in parallel, and why GET requests can be cached and retried. A resolver for a query field that writes (a "mark as read" on me) breaks that contract.
Definition: Execution walks the selection set depth-first, calling a resolver per field. The spec says of mutations: "This selection set should be executed serially." Queries may execute in parallel, which gqlgen does for fields with resolvers. A field error does not stop siblings: "A response may contain both a partial response as well as any field errors in the case that a field error was raised on a field and was replaced with null."
query { book(id:"b1") { title author { name } } }
1 parse + validate against the SDL (errors here: no data at all)
2 Query.book resolver runs -> Book b1
3 Book.title: struct field, no resolver
4 Book.author resolver runs -> Loader.Load("a1")
5 Author.name: struct field
6 response { "data": { "book": { ... } } }Real scenario: a page loads me, notifications and feed in one query: three independent resolvers run in parallel, and if notifications fails the user still sees the feed. A checkout runs mutation { reserveStock(...) createOrder(...) }: the two top-level fields run in order, so the second can rely on the first.
| Operation | Executed | Idempotent by convention | Transport |
|---|---|---|---|
query | Fields may run in parallel | Yes | POST, GET |
mutation | Top-level fields serially | No | POST |
subscription | One resolver returns a channel; each value is executed | n/a | WebSocket (or SSE) |
Fix / how to use it: put every write in a mutation, return the changed object so the client can update its cache, and never rely on parallel field order for correctness. The spec text is in the Execution section of spec.graphql.org.
gqlgen: config and codegen Must-know
In plain words: You write the schema and a small config file, run one command, and gqlgen writes the boring Go: the executable schema, the model structs and a stub for every resolver you still need to implement.
Common misunderstanding: "Generated code means I edit it." Never edit generated.go or models_gen.go; they are rewritten on every run. You edit schema.graphql, the config, your own types and the resolver bodies.
Definition: gqlgen.yml lists the schema files, where to write the executable schema (exec), where to write generated models (model), the resolver layout (follow-schema writes one *.resolvers.go per schema file; single-file writes one) and two mapping tools. autobind lists Go packages: if a type with the schema type's name exists there, gqlgen uses it instead of generating one. models maps a schema type to specific Go types, which is how custom scalars and enums bind. go generate runs gqlgen generate; since Go 1.24 the tool is declared with a tool directive in go.mod and run as go tool gqlgen generate ("Go modules can now track executable dependencies using tool directives in go.mod").
# gqlgen.yml: where the schema lives and where generated code goes.
schema:
- graph/*.graphql
exec:
filename: graph/generated.go
package: graph
model:
filename: graph/model/models_gen.go
package: model
resolver:
layout: follow-schema
dir: graph
package: graph
filename_template: "{name}.resolvers.go"
# autobind: if a Go type with the same name as a schema type exists in
# these packages, gqlgen uses it instead of generating a struct.
autobind:
- academy/graphql-in-go/graph/model
# models: explicit schema type -> Go type mapping (custom scalars here).
models:
ID:
model:
- github.com/99designs/gqlgen/graphql.ID
Time:
model:
- github.com/99designs/gqlgen/graphql.Time
UUID:
model:
- academy/graphql-in-go/graph/model.UUID1 edit graph/schema.graphql
2 GOTOOLCHAIN=go1.24.13 go generate ./graph # runs: go tool gqlgen generate
3 gqlgen loads the SDL, binds each type/field to Go (autobind, models, struct fields, methods)
4 writes graph/generated.go and graph/model/models_gen.go
5 for every field that needs a resolver, adds a method stub to graph/*.resolvers.go
6 you fill in the stub bodies; regeneration preserves themTwo sharp edges were hit while building this chapter, and both are worth knowing. First, a helper method in schema.resolvers.go is moved into a comment block when gqlgen regenerates (the file says "The code below was going to be deleted when updating resolvers"), so helpers belong in their own file; the chapter keeps connection in graph/connection.go. Second, a Resolver field named like a schema field is shadowed: the generated queryResolver has a method Books, which hides a promoted Resolver.Books field, so the injected services are called AuthorSvc and BookSvc.
| Config key | Meaning | This chapter |
|---|---|---|
schema | Glob of .graphql files | graph/*.graphql |
exec | Executable schema output | graph/generated.go, package graph |
model | Generated models output | graph/model/models_gen.go |
resolver.layout | follow-schema or single-file | follow-schema |
autobind | Packages searched for same-named Go types | academy/graphql-in-go/graph/model |
models | Explicit schema-to-Go type mapping | ID, Time, UUID |
What generation costs on this machine. With the pinned gqlgen v0.17.86, go tool gqlgen generate under Go 1.27.4 fails with internal error: package "github.com/vektah/gqlparser/v2/ast" without types was imported from "github.com/99designs/gqlgen/graphql/introspection" (the older golang.org/x/tools inside that gqlgen cannot read the newer toolchain's export data), and in this run the failed command also removed generated.go. Running it as GOTOOLCHAIN=go1.24.13 go tool gqlgen generate works and is idempotent. Upgrading gqlgen instead means a newer go line in your go.mod.
Fix / how to use it: commit the generated files, run generation in CI and fail the build on a diff (git diff --exit-code), and pin the gqlgen version in go.mod with go get -tool github.com/99designs/gqlgen@v0.17.86.
Schema-first vs code-first Important
In plain words: In schema-first you write the GraphQL SDL and the tool gives you Go. In code-first you write Go (structs or builder calls) and the tool derives the schema from it.
Common misunderstanding: "Code-first is more Go-like, so it is safer." Safety comes from the compiler checking resolvers against the schema, and which side writes the other matters less. gqlgen's comparison page rates itself with type safety and type binding; it rates graphql-go/graphql's run-time types without either.
Definition: Four Go options and how the gqlgen comparison page (and each README) describes them:
| Library | Style | How resolvers attach | Notable |
|---|---|---|---|
github.com/99designs/gqlgen | Schema first, code generation | Generated interfaces you implement; struct fields bound automatically | Generated enums and inputs, federation, complexity limits, custom errors with path |
github.com/graph-gophers/graphql-go | Schema first, run time | "resolvers are matched to the schema based on method sets"; "schema type-checking against resolvers" | Minimal API, OpenTelemetry support, parallel resolvers |
github.com/graphql-go/graphql | Code first, run time types | graphql.Field with a Resolve: func(p graphql.ResolveParams) (interface{}, error) | Port of the JS reference implementation; no compile-time binding |
thunder | Struct first | Methods on structs | Listed in gqlgen's comparison, not used here |
// code-first (graphql-go/graphql): the schema is built by Go calls at run time
fields := graphql.Fields{"hello": &graphql.Field{
Type: graphql.String,
Resolve: func(p graphql.ResolveParams) (interface{}, error) { return "world", nil },
}}
-> type errors in the resolver surface only when the query runsReal scenario: a team that wants the schema reviewed by frontend developers without reading Go picks schema-first, because the .graphql file is the artifact reviewed in the pull request. A team whose domain model is already a rich Go struct graph may prefer a library that derives types from structs.
| Concern | gqlgen | graph-gophers | graphql-go/graphql |
|---|---|---|---|
| Compile-time check resolver vs schema | Yes (generated interfaces) | At schema load | No |
| Generated code | Yes, thousands of lines | None | None |
| Subscriptions | Built in (WebSocket, SSE transports) | Via a separate transport package | Supported |
| Federation | Plugin | No | No |
Fix / how to use it: if you are starting a new service, take gqlgen unless a constraint (no codegen allowed, tiny API) says otherwise; the rest of this page assumes it. Compare against the current comparison page before deciding, since it changes with releases.
Resolver DI: the Resolver struct Must-know
In plain words: gqlgen asks for one object, Resolver, and hands it to every resolver. Whatever the resolvers need (a database, a user service, a message broker) is a field on that struct, set once at start-up.
Common misunderstanding: "gqlgen does dependency injection for me." It does not construct anything. It calls the Resolver you give it; you build that value in main (or with Wire/fx) from concrete services, exactly like any other Go handler.
Definition: the generated ResolverRoot interface has one accessor per type with resolver methods (Query(), Mutation(), Author(), Book(), Subscription()). The conventional implementation is type Resolver struct{ ... } with methods that return thin wrappers embedding *Resolver. Depend on small interfaces defined next to the consumer, so tests can pass fakes and the generated code never imports your database package.
package graph
// Regenerate with a Go toolchain that gqlgen's golang.org/x/tools can read
// (on Go 1.27.4 the pinned v0.17.86 fails and deletes generated.go):
//
// GOTOOLCHAIN=go1.24.13 go generate ./graph
//
//go:generate go tool gqlgen generate
import (
"context"
"academy/graphql-in-go/graph/model"
)
// The resolvers depend on these small interfaces, not on a database. That is
// the whole DI story: gqlgen never constructs the Resolver, you do.
// AuthorService is what the resolvers need to know about authors.
type AuthorService interface {
AuthorByID(ctx context.Context, id string) (*model.Author, error)
SearchAuthors(ctx context.Context, term string) ([]*model.Author, error)
}
// BookService is what the resolvers need to know about books.
type BookService interface {
BookByID(ctx context.Context, id string) (*model.Book, error)
// BooksPage is keyset pagination; authorID == "" means every author.
BooksPage(ctx context.Context, authorID, afterID string, first int) (page []*model.Book, hasNext bool, total int, err error)
SearchBooks(ctx context.Context, term string) ([]*model.Book, error)
AddBook(ctx context.Context, in model.NewBook) (*model.Book, error)
Rating(ctx context.Context, bookID string) (float64, error)
}
// Broker fans published books out to live subscriptions.
type Broker interface {
Publish(b *model.Book)
Subscribe(ctx context.Context) <-chan *model.Book
}
// Resolver is the root of every resolver. gqlgen embeds a pointer to it in
// the generated per-type resolvers, so every resolver reaches the services
// through r.AuthorSvc, r.BookSvc and r.Events (never name a field after a schema field such as Books: the generated resolver method shadows it).
type Resolver struct {
AuthorSvc AuthorService
BookSvc BookService
Events Broker
}main
1 db := store.NewMemory() ; ev := store.NewBroker()
2 r := &graph.Resolver{AuthorSvc: db, BookSvc: db, Events: ev}
3 cfg := graph.Config{Resolvers: r}; cfg.Directives.Auth = graph.Auth
4 srv := handler.New(graph.NewExecutableSchema(cfg))
5 per request: bookResolver{r}.Author(ctx, obj) -> r.AuthorSvc / loaders.For(ctx)Real scenario: server.New takes the server.Services interface (the author, book and loader-fetch methods), not *store.Memory, so swapping the in-memory store for a Postgres-backed one changes one line in main; the server tests prove it by passing a spyStore wrapper that satisfies the same interface; a unit test passes a fake BookService whose Rating returns an error to exercise the partial-response path; the same Resolver is built twice in tests with different fakes.
| Wiring style | Good for | Cost |
|---|---|---|
Struct literal in main | Most services | You write the wiring |
Constructor graph.NewResolver(deps) | Validation of required deps | One more function |
| Wire / fx | Large graphs | Another tool; see Mocking with Interfaces & DI |
| Global variables | Never | Hidden coupling, untestable |
Fix / how to use it: keep the Resolver free of business logic; it translates GraphQL arguments to service calls and service results to GraphQL types. Business rules belong in the service so REST, gRPC and GraphQL can share them (A REST API in Go shows the layering).
Context in resolvers Must-know
In plain words: Every resolver gets a ctx as its first argument. It is cancelled when the client goes away, carries the logged-in user, and is where the dataloaders and the field's path live.
Common misunderstanding: "I can start a new context.Background() in a resolver for the database call." That cuts the call off from the client's cancellation and deadline; a long query keeps running after the browser closed the tab.
Definition: the ctx is derived from the HTTP request's context, so everything in context applies. gqlgen adds three things to it: the operation context (graphql.GetOperationContext(ctx): the parsed operation, variables, stats), the field context (graphql.GetFieldContext(ctx): the current object, field, path) and the error collector (graphql.AddError(ctx, err) adds an error without returning, and graphql.GetPath(ctx) gives the path). Your middleware adds request-scoped values (role, dataloaders).
1 http.Server accepts request, r.Context() cancelled if the client disconnects
2 RoleMiddleware: ctx = WithRole(r.Context(), role)
3 loaders.Middleware: ctx = WithValue(ctx, ctxKey{}, NewLoaders())
4 handler.Server: ctx = WithOperationContext(...)
5 field execution: ctx = WithFieldContext(...) per field
6 resolver(ctx, obj, args) -> pass ctx to services, loaders, the databaseReal scenario: the client closes the tab during a slow books query; the cancelled ctx reaches QueryContext and the database stops. A resolver reads the user's role from ctx to decide whether to include draft books. A deadline set once in middleware bounds the whole operation.
What lives in ctx | Set by | Read by |
|---|---|---|
| Cancellation, deadline | net/http server, your timeout middleware | Services, drivers |
| Authenticated principal / role | Your auth middleware | Directives, services |
| Dataloaders | Your loaders middleware | Field resolvers |
| Operation and field context | gqlgen | Extensions, tracing, graphql.GetPath |
Fix / how to use it: pass ctx first and unchanged to every service; store request-scoped values behind unexported key types with accessors (as graph.WithRole / graph.RoleFrom do); never keep a ctx in a struct.
Field-level resolvers Must-know
In plain words: A field that is just a struct field is read directly. A field that needs real work (another query, another service) gets its own function, called only when the client actually asks for that field.
Common misunderstanding: "Resolvers run for every field." Plain struct fields are bound by name and cost nothing. gqlgen generates a resolver method only when the Go type has no matching field or method, or when you force one.
Definition: @goField(forceResolver: true) on a field tells gqlgen to generate a resolver method even if the Go struct has a matching field. The chapter's Book.author and Author.books use it: Book stores only AuthorID, and the author is fetched on demand. In models_gen.go terms, no resolver is generated for Book.title.
query { book(id:"b1") { title } } # Book.author never runs
query { book(id:"b1") { title author { name } } } # Book.author runs once
query { books(first:6) { edges { node { author { name } } } } } # Book.author x6Real scenario: an Order type with total (stored) and items (a separate table): items is a field resolver, so listing orders without selecting items never touches the items table. viewerHasLiked is a resolver that needs the current user from ctx.
| Field kind | Cost when not selected | Cost when selected |
|---|---|---|
| Struct field | None | None |
| Method on the model | None | A method call |
| Field resolver | None | A function call, maybe a query |
| Field resolver in a list of N | None | N calls (N+1 risk) |
package graph
// This file will be automatically regenerated based on the schema, any resolver
// implementations
// will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.86
import (
"academy/graphql-in-go/graph/model"
"academy/graphql-in-go/loaders"
"context"
)
// Books is the resolver for the books field.
func (r *authorResolver) Books(ctx context.Context, obj *model.Author, first *int, after *string) (*model.BookConnection, error) {
return r.connection(ctx, obj.ID, first, after)
}
// Author is the resolver for the author field. It does not hit the service:
// it asks the per-request dataloader, which batches all authors of one query
// into a single AuthorsByIDs call.
func (r *bookResolver) Author(ctx context.Context, obj *model.Book) (*model.Author, error) {
return loaders.For(ctx).Author.Load(ctx, obj.AuthorID)
}
// Rating is the resolver for the rating field.
func (r *bookResolver) Rating(ctx context.Context, obj *model.Book) (*float64, error) {
v, err := r.BookSvc.Rating(ctx, obj.ID)
if err != nil {
return nil, err // field is nullable: null + one entry in "errors"
}
return &v, nil
}
// AddBook is the resolver for the addBook field.
func (r *mutationResolver) AddBook(ctx context.Context, input model.NewBook) (*model.Book, error) {
b, err := r.BookSvc.AddBook(ctx, input)
if err != nil {
return nil, err
}
r.Events.Publish(b)
return b, nil
}
// Book is the resolver for the book field.
func (r *queryResolver) Book(ctx context.Context, id string) (*model.Book, error) {
b, err := r.BookSvc.BookByID(ctx, id)
if err != nil {
return nil, err
}
return b, nil
}
// Books is the resolver for the books field.
func (r *queryResolver) Books(ctx context.Context, first *int, after *string) (*model.BookConnection, error) {
return r.connection(ctx, "", first, after)
}
// Search is the resolver for the search field.
func (r *queryResolver) Search(ctx context.Context, term string) ([]model.SearchResult, error) {
var out []model.SearchResult
authors, err := r.AuthorSvc.SearchAuthors(ctx, term)
if err != nil {
return nil, err
}
for _, a := range authors {
out = append(out, a)
}
books, err := r.BookSvc.SearchBooks(ctx, term)
if err != nil {
return nil, err
}
for _, b := range books {
out = append(out, b)
}
return out, nil
}
// SecretShelf is the resolver for the secretShelf field.
func (r *queryResolver) SecretShelf(ctx context.Context) ([]*model.Book, error) {
page, _, _, err := r.BookSvc.BooksPage(ctx, "", "", 100)
return page, err
}
// BookAdded is the resolver for the bookAdded field. The returned channel is
// owned by the resolver; gqlgen reads it until ctx is done (client left).
func (r *subscriptionResolver) BookAdded(ctx context.Context) (<-chan *model.Book, error) {
return r.Events.Subscribe(ctx), nil
}
// Author returns AuthorResolver implementation.
func (r *Resolver) Author() AuthorResolver { return &authorResolver{r} }
// Book returns BookResolver implementation.
func (r *Resolver) Book() BookResolver { return &bookResolver{r} }
// Mutation returns MutationResolver implementation.
func (r *Resolver) Mutation() MutationResolver { return &mutationResolver{r} }
// Query returns QueryResolver implementation.
func (r *Resolver) Query() QueryResolver { return &queryResolver{r} }
// Subscription returns SubscriptionResolver implementation.
func (r *Resolver) Subscription() SubscriptionResolver { return &subscriptionResolver{r} }
type authorResolver struct{ *Resolver }
type bookResolver struct{ *Resolver }
type mutationResolver struct{ *Resolver }
type queryResolver struct{ *Resolver }
type subscriptionResolver struct{ *Resolver }Fix / how to use it: make a field a resolver when its data is expensive or optional; batch it with a dataloader the moment it is used in a list.
Dataloaders: ending N+1 Must-know
In plain words: A dataloader is a waiting room for lookups. Instead of every list item running its own query, each one drops its key into the loader; after a few milliseconds the loader asks the database once for all the keys and hands each item its answer.
Common misunderstanding: "A dataloader is a cache, so I can make it global." It does cache within its lifetime, but it exists to batch within one request. The dataloadgen README states the lifetime rule: "A Loader object is created per graphql request." A global loader would serve one user's data to another and never see updates.
Definition: the N+1 problem is one query for a list plus one per item. gqlgen's own docs describe the fix: "Dataloaders consolidate the retrieval of information into fewer, batched calls." The loader has a fetch(ctx, keys) (values, errs) function; the contract from the README is "The order of the keys must match the order of the values." Two Go libraries exist: github.com/vikstrous/dataloadgen (generics-based, the one gqlgen's docs now use; v0.0.10 here, default wait 16 ms and unlimited batch size unless you pass WithBatchCapacity, per its source at tag v0.0.10) and github.com/graph-gophers/dataloader/v7 (a port of Facebook's DataLoader; its README warns its cache is "intended only to be used for short lived DataLoaders (i.e. DataLoaders that only exist for the life of an http request)").
Book.author for 6 books, one request, one loader
1 t=0.0ms resolver(b1) -> Load("a1") starts a batch, timer 2 ms
2 t=0.0ms resolver(b2) -> Load("a2") joins the batch
3 t=0.0ms resolver(b3) -> Load("a3") joins the batch
4 t=0.0ms resolver(b4) -> Load("a1") same key: deduplicated
5 t=2.0ms timer fires -> fetch(ctx, ["a1","a2","a3"]) -> ONE query
6 t=2.4ms values fan back out to the six waiting resolversReal scenario: a feed of 50 posts each showing the author, the like count and the viewer's reaction: three loaders turn 150 queries into 3. A list of orders with a customer field: one WHERE id = ANY($1) instead of one query per order. A permission check inside a field resolver that hits a policy service: batch the check.
| Aspect | dataloadgen | graph-gophers/dataloader v7 |
|---|---|---|
| API | NewLoader[K, V](fetch, opts...), Load(ctx, key), LoadAll, Prime, Clear | NewBatchedLoader(batchFn, opts...), Load(ctx, key) returns a thunk you call: thunk := loader.Load(ctx, 5); v, err := thunk() |
| Fetch signature | func(ctx, []K) ([]V, []error) or a mapped variant returning a map | func(ctx, []K) []*Result[V] |
| Missing key | dataloadgen.ErrNotFound (mapped loader) | Result with an error |
| Tracing | WithTracer(trace.Tracer) (OpenTelemetry) | Not documented in its README |
| Cache | Per loader, per request | In-memory, short-lived by README |
// Package loaders attaches one dataloader per HTTP request to the context.
package loaders
import (
"context"
"net/http"
"time"
"academy/graphql-in-go/graph/model"
"github.com/vikstrous/dataloadgen"
)
// AuthorFetcher is the batched query the loader calls once per batch.
type AuthorFetcher interface {
AuthorsByIDs(ctx context.Context, ids []string) ([]*model.Author, error)
}
// Loaders bundles every loader of one request.
type Loaders struct {
Author *dataloadgen.Loader[string, *model.Author]
}
type ctxKey struct{}
// New builds fresh loaders. Create them per request: the cache must not
// outlive the request, or one user could see another user's data.
func New(f AuthorFetcher, wait time.Duration) *Loaders {
fetch := func(ctx context.Context, ids []string) ([]*model.Author, []error) {
authors, err := f.AuthorsByIDs(ctx, ids)
if err != nil {
errs := make([]error, len(ids))
for i := range errs {
errs[i] = err
}
return nil, errs
}
errs := make([]error, len(ids))
for i, a := range authors {
if a == nil {
errs[i] = dataloadgen.ErrNotFound
}
}
return authors, errs
}
return &Loaders{
Author: dataloadgen.NewLoader(fetch,
dataloadgen.WithWait(wait),
dataloadgen.WithBatchCapacity(100),
),
}
}
// Middleware stores a fresh *Loaders in every request context.
func Middleware(f AuthorFetcher, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
l := New(f, 2*time.Millisecond)
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, l)))
})
}
// For returns the request's loaders; it panics if the middleware is missing,
// which is a wiring bug and should fail loudly in tests.
func For(ctx context.Context) *Loaders {
l, ok := ctx.Value(ctxKey{}).(*Loaders)
if !ok {
panic("loaders: middleware not installed")
}
return l
}Where the loader is used, the resolver is one line, shown in the resolvers file above: loaders.For(ctx).Author.Load(ctx, obj.AuthorID). The server test then asserts the cost end to end:
data, errs := e.run(t, `{ books(first: 6) { totalCount edges { node { title author { name } } } } }`)
st := e.db.Stats()
// st.BookQueries == 1 && st.AuthorQueries == 1: ONE batched author query-- what each loader batch should turn into, PostgreSQL
SELECT id, name FROM authors WHERE id = ANY($1); -- $1 = ['a1','a2','a3']
-- the N+1 shape you are removing
SELECT id, name FROM authors WHERE id = $1; -- executed once per bookFix / how to use it: one loader per entity per request; construct them in HTTP middleware and read them with a helper that panics loudly when the middleware is missing (a wiring bug); make the fetch function return results in key order, with a nil or an error for each missing key; treat the wait window as a latency/batching trade-off (2 ms here, 16 ms library default); and assert query counts in tests, as the test above does. Loaders fix many-to-one and one-to-many lookups by key; they do not make an unbounded list cheap (see limits).
Custom scalars Important
In plain words: A scalar is a leaf value with a special text form on the wire: a timestamp, a UUID, a money amount. You teach gqlgen how to write it out and how to read it back.
Common misunderstanding: "I must write my own Time and UUID." gqlgen ships helpers for common cases: its scalars page says it ships helpers for "Int64, Time, Any, Upload and Map", that Time "adheres to the time.RFC3339Nano format" and that UUID maps to uuid.UUID; in v0.17.86 the source has graphql/uuid.go with MarshalUUID and UnmarshalUUID. This chapter writes its own UUID anyway, because a custom scalar's contract (a Go type plus a marshaler plus an unmarshaler) is worth seeing once.
Definition: declare scalar UUID in SDL, map it in gqlgen.yml under models to a Go type, and provide MarshalUUID(v UUID) graphql.Marshaler and UnmarshalUUID(v any) (UUID, error) in that package. gqlgen looks them up by the name Marshal<Scalar> and Unmarshal<Scalar>. The unmarshaler receives the decoded JSON value (string, float64, bool, map...), so it must type-check; returning an error produces a validation error before any resolver runs.
SDL scalar UUID
yml models: UUID: model: [ academy/graphql-in-go/graph/model.UUID ]
output book.externalId (uuid.UUID) --MarshalUUID--> "123e4567-e89b-12d3-a456-426614174000"
input "123e4567-..." --UnmarshalUUID--> uuid.UUID, or: UUID must be a string, got float64Real scenario: Time for publishedAt (always UTC RFC 3339 on the wire, never a Unix integer a client must guess the unit of); UUID for external ids; Money as a string-encoded decimal so floating point never touches currency; Cursor as an opaque string type; Upload for multipart file uploads.
| Scalar | Built into gqlgen v0.17.86 | Go type | Wire form |
|---|---|---|---|
Int, Float, String, Boolean, ID | Yes (spec) | int, float64, string, bool, string | JSON |
Time | graphql.Time | time.Time | RFC 3339 with nanoseconds |
UUID | graphql.UUID (also here as a custom one) | uuid.UUID | canonical string |
Int64, Uint, Any, Map, Upload | Yes | int64, uint, any, map[string]any, graphql.Upload | JSON / multipart |
// Package model holds the hand-written domain types that gqlgen binds to
// (via autobind) plus the custom scalar marshalers.
package model
import (
"fmt"
"io"
"github.com/99designs/gqlgen/graphql"
"github.com/google/uuid"
)
// UUID is the Go type behind the UUID scalar.
type UUID = uuid.UUID
// MarshalUUID is looked up by gqlgen as Marshal<ScalarName>.
func MarshalUUID(u UUID) graphql.Marshaler {
return graphql.WriterFunc(func(w io.Writer) {
_, _ = io.WriteString(w, `"`+u.String()+`"`)
})
}
// UnmarshalUUID turns the JSON value of an argument or variable into a UUID.
func UnmarshalUUID(v any) (UUID, error) {
s, ok := v.(string)
if !ok {
return UUID{}, fmt.Errorf("UUID must be a string, got %T", v)
}
return uuid.Parse(s)
}Fix / how to use it: prefer the built-in scalar when one fits; write a custom one when the wire format is yours (money, cursors, geo points); always test the unmarshaler with wrong types (the chapter's TestUUIDScalar passes 42, "not-a-uuid" and nil).
Directives: @goField and a custom @auth Important
In plain words: A directive is a sticky note on a field in the schema: "check the role before running this", "generate a resolver for this". The behaviour lives in Go, the note lives in the SDL, so every reader of the schema sees the rule.
Common misunderstanding: "Directives are a full middleware system." The gqlgen docs say the implementation "is still fairly limited, and is designed to cover the most common “field middleware” case". They wrap one field or argument, not a whole operation (that is an extension).
Definition: a directive is declared (directive @auth(role: Role!) on FIELD_DEFINITION), applied (addBook(input: NewBook!): Book! @auth(role: EDITOR)) and implemented as a function assigned to Config.Directives.Auth. The signature gqlgen generates is func(ctx, obj any, next graphql.Resolver, role Role) (any, error). The docs spell out the rule that matters: "You can block access to the field by not calling next(ctx)". @goField is a built-in one with options forceResolver and name that controls binding; it is a codegen-time directive, not run per request.
package graph
import (
"context"
"errors"
"net/http"
"academy/graphql-in-go/graph/model"
"github.com/99designs/gqlgen/graphql"
"github.com/vektah/gqlparser/v2/gqlerror"
)
type roleKey struct{}
// WithRole stores the caller's role in the context.
func WithRole(ctx context.Context, r model.Role) context.Context {
return context.WithValue(ctx, roleKey{}, r)
}
// RoleFrom returns the caller's role, if any.
func RoleFrom(ctx context.Context) (model.Role, bool) {
r, ok := ctx.Value(roleKey{}).(model.Role)
return r, ok
}
// RoleMiddleware is a stand-in for real authentication. A production server
// verifies a session cookie or JWT here and stores the verified principal.
func RoleMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if v := r.Header.Get("X-Demo-Role"); v != "" {
r = r.WithContext(WithRole(r.Context(), model.Role(v)))
}
next.ServeHTTP(w, r)
})
}
// Auth implements the @auth(role: ...) schema directive. gqlgen calls it
// before the field resolver; not calling next stops the field.
func Auth(ctx context.Context, _ any, next graphql.Resolver, role model.Role) (any, error) {
have, ok := RoleFrom(ctx)
if !ok {
return nil, &gqlerror.Error{
Message: "authentication required",
Extensions: map[string]any{"code": "UNAUTHENTICATED"},
}
}
if have.Rank() < role.Rank() {
return nil, &gqlerror.Error{
Message: "forbidden: requires role " + string(role),
Extensions: map[string]any{"code": "FORBIDDEN"},
}
}
return next(ctx)
}
// ErrBadInput marks errors caused by the client's arguments.
var ErrBadInput = errors.New("bad input")query { secretShelf { title } } (header X-Demo-Role absent)
1 Query.secretShelf has @auth(role: READER)
2 gqlgen calls Auth(ctx, obj, next, READER)
3 RoleFrom(ctx) -> not set -> return UNAUTHENTICATED, next is NOT called
4 response: { "data": null, "errors": [ { "message": "authentication required", "path": ["secretShelf"] } ] }Real scenario: @auth(role: ADMIN) on a deleteUser mutation; @deprecated(reason: "Use addBook") for evolution; a hint directive such as @cacheControl(maxAge: 60) that a response extension turns into a Cache-Control header; an input-validation directive on arguments (ARGUMENT_DEFINITION).
| Directive location | Use | Called per request? |
|---|---|---|
FIELD_DEFINITION | Permissions, caching hints | Yes, around the resolver |
ARGUMENT_DEFINITION, INPUT_FIELD_DEFINITION | Validation | Yes, when the argument is present |
OBJECT, ENUM_VALUE | Documentation, tooling | Not by gqlgen (introspection only) |
@goField | Binding hints for codegen | No, generation time |
Fix / how to use it: use @auth for the coarse rule ("must be signed in", "must be an editor") and put the fine rule ("this user may edit this book") in the service layer; see Authentication and authorization. Every directive must be assigned in Config.Directives: an unassigned one makes every field that uses it fail at request time with directive auth is not implemented (the text in the generated code), so a test per directive is cheap insurance.
Authentication and authorization Must-know
In plain words: Authentication answers "who is this?", and it happens once per HTTP request, before GraphQL runs. Authorization answers "may this person see this thing?", and it has to happen per object, close to the data, because GraphQL lets a client reach the same object by many paths.
Common misunderstanding: "I protected Query.secretShelf, so the secret books are safe." Another field may return the same book (author { books }, search, a mutation's payload). Authorization attached only to one entry point leaks through the graph. graphql.org says "for a production codebase, delegate authorization logic to the business logic layer".
Definition: three places, three jobs. HTTP middleware verifies the session cookie or token and puts the principal in ctx (Authentication in Go). A directive makes a coarse decision declaratively. The service layer enforces per-object rules and is the same code REST and gRPC use. The chapter's RoleMiddleware reads a demo header; a real one verifies a signed token.
POST /query Cookie: session=...
1 AuthMiddleware: verify cookie -> principal{ID, Role}; ctx = WithPrincipal(ctx, p)
2 gqlgen executes: field has @auth(role: EDITOR)? directive checks the role from ctx
3 resolver calls BookService.Update(ctx, id, in)
4 service: p := PrincipalFrom(ctx); if !p.CanEdit(book) { return ErrForbidden }Real scenario: an Order.invoiceUrl field visible only to the order's owner and to admins; a User.email visible to the user and to support staff; a multi-tenant API where every service query carries a tenant_id from ctx.
| Layer | Decides | Bypass risk |
|---|---|---|
| HTTP middleware | Who you are | None if verified; anonymous allowed through |
@auth directive | Role on this field | Other fields returning the same data |
| Service layer | May this principal touch this object | None: all entry points use it |
| Database (row-level security) | Last line of defence | Only misconfigured roles |
Fix / how to use it: authenticate in middleware, authorize in services, use directives for role gates, and test the negative case for every mutation (the chapter's TestAuthDirective checks anonymous, reader and editor). For browser sessions remember CSRF and CORS; for tokens, see JWT deep dive.
Errors: gqlerror, extensions, partial responses Must-know
In plain words: In GraphQL a failed field does not fail the whole request. The failed field becomes null, an entry is added to errors, and everything else still arrives. The HTTP status is usually still 200.
Common misunderstanding: "Any error means the response is invalid, so the client should throw away the data." The spec defines partial responses on purpose; a client must read both data and errors. And the opposite mistake: "errors are exceptions, so I should return HTTP 500". Clients and gateways that see 500 may retry or hide the body.
Definition: the error type is *gqlerror.Error from github.com/vektah/gqlparser/v2/gqlerror with Message, Path, Locations and Extensions (a free-form map; code is the convention). A resolver returns a plain Go error, which gqlgen wraps; it can also call graphql.AddError(ctx, err) to record several errors for one field. The gqlgen docs warn: "The assumption is that any error message returned here is appropriate for end users. If certain messages aren't safe, customise the error presenter." The spec: "A response may contain both a partial response as well as any field errors in the case that a field error was raised on a field and was replaced with null."
// Package server wires the executable schema, its extensions and the HTTP
// middleware into one http.Handler. main would do exactly this and call
// http.ListenAndServe; tests call it with httptest.
package server
import (
"context"
"errors"
"net/http"
"strings"
"time"
"academy/graphql-in-go/graph"
"academy/graphql-in-go/limits"
"academy/graphql-in-go/loaders"
"academy/graphql-in-go/store"
"academy/graphql-in-go/tracing"
"github.com/99designs/gqlgen/graphql"
"github.com/99designs/gqlgen/graphql/handler"
"github.com/99designs/gqlgen/graphql/handler/extension"
"github.com/99designs/gqlgen/graphql/handler/lru"
"github.com/99designs/gqlgen/graphql/handler/transport"
"github.com/99designs/gqlgen/graphql/playground"
"github.com/gorilla/websocket"
"github.com/vektah/gqlparser/v2/ast"
"github.com/vektah/gqlparser/v2/gqlerror"
"go.opentelemetry.io/otel/trace"
)
// Config holds the knobs that differ between development and production.
type Config struct {
Production bool // disables introspection and the playground
ComplexityLimit int // 0 means the default of 200
DepthLimit int // 0 means the default of 8
// Tracer, when set, adds one OpenTelemetry span per operation and per
// resolver field. Pass otel.Tracer("graphql") in main.
Tracer trace.Tracer
}
// Services is everything the handler needs from the data layer. Any type
// with these methods works: store.Memory here, a PostgreSQL repository later.
type Services interface {
graph.AuthorService
graph.BookService
loaders.AuthorFetcher
}
// New builds the handler tree: /query (GraphQL) and /playground (dev only).
func New(cfg Config, db Services, events graph.Broker) http.Handler {
if cfg.ComplexityLimit == 0 {
cfg.ComplexityLimit = 200
}
if cfg.DepthLimit == 0 {
cfg.DepthLimit = 8
}
// Dependency injection: the Resolver is built here, by hand, from the
// concrete services. gqlgen only ever sees the interfaces.
resolver := &graph.Resolver{AuthorSvc: db, BookSvc: db, Events: events}
gcfg := graph.Config{Resolvers: resolver}
gcfg.Directives.Auth = graph.Auth
gcfg.Complexity.Query.Books = func(child int, first *int, _ *string) int {
return pageSize(first) * child // cost grows with the page size
}
gcfg.Complexity.Author.Books = func(child int, first *int, _ *string) int {
return pageSize(first) * child
}
srv := handler.New(graph.NewExecutableSchema(gcfg))
// Transports are tried in order; WebSocket goes first, as the gqlgen
// subscriptions recipe says, so an upgrade request never reaches GET/POST.
srv.AddTransport(transport.Websocket{
KeepAlivePingInterval: 10 * time.Second,
Upgrader: websocket.Upgrader{
// A real server checks the Origin against an allow-list.
CheckOrigin: func(*http.Request) bool { return true },
},
})
srv.AddTransport(transport.Options{})
srv.AddTransport(transport.GET{})
srv.AddTransport(transport.POST{})
srv.SetQueryCache(lru.New[*ast.QueryDocument](1000))
srv.Use(extension.AutomaticPersistedQuery{Cache: lru.New[string](100)})
srv.Use(extension.FixedComplexityLimit(cfg.ComplexityLimit))
srv.Use(limits.Depth{Max: cfg.DepthLimit})
if !cfg.Production {
srv.Use(extension.Introspection{})
} else {
srv.SetDisableSuggestion(true) // no "Did you mean ...?" schema leaks
}
if cfg.Tracer != nil {
srv.Use(tracing.Extension{Tracer: cfg.Tracer})
}
srv.SetErrorPresenter(presentError)
srv.SetRecoverFunc(func(_ context.Context, err any) error {
// Never leak panic details to the client; log err in real code.
return gqlerror.Errorf("internal server error")
})
mux := http.NewServeMux()
var gql http.Handler = srv
gql = graph.RoleMiddleware(gql)
gql = loaders.Middleware(db, gql)
mux.Handle("/query", gql)
if !cfg.Production {
mux.Handle("/playground", playground.Handler("Library", "/query"))
}
return mux
}
func pageSize(first *int) int {
if first == nil {
return 10
}
return *first
}
// presentError is the last stop before an error reaches the client. It maps
// domain errors to stable extensions.code values and hides unexpected
// resolver errors. Parse and validation errors (no path) pass through.
func presentError(ctx context.Context, err error) *gqlerror.Error {
gqlErr := graphql.DefaultErrorPresenter(ctx, err)
if gqlErr.Extensions == nil {
gqlErr.Extensions = map[string]any{}
}
if _, set := gqlErr.Extensions["code"]; set {
return gqlErr // validation, auth, complexity: already coded
}
switch {
case errors.Is(err, store.ErrNotFound):
gqlErr.Extensions["code"] = "NOT_FOUND"
case errors.Is(err, graph.ErrBadInput):
gqlErr.Extensions["code"] = "BAD_USER_INPUT"
case isIntrospection(gqlErr):
gqlErr.Extensions["code"] = "INTROSPECTION_DISABLED"
case len(gqlErr.Path) > 0:
// An unexpected error from a resolver: log err, hide the details.
gqlErr.Message = "internal server error"
gqlErr.Extensions["code"] = "INTERNAL_SERVER_ERROR"
}
return gqlErr
}
// isIntrospection reports whether the error belongs to a __schema or __type
// field, the ones gqlgen refuses when the Introspection extension is absent.
func isIntrospection(e *gqlerror.Error) bool {
if len(e.Path) == 0 {
return false
}
name, ok := e.Path[0].(ast.PathName)
return ok && strings.HasPrefix(string(name), "__")
}The presentError function above is the error presenter: it maps store.ErrNotFound to NOT_FOUND, graph.ErrBadInput to BAD_USER_INPUT, leaves already-coded errors (auth, limits) alone, and replaces any other resolver error with internal server error so a database message never reaches a client. The server's SetRecoverFunc does the same for panics.
query { book(id: "b3") { title rating } }
1 Query.book -> Book b3
2 Book.title -> "Go To Considered"
3 Book.rating resolver -> ratings service returns error
4 rating is nullable -> null, error recorded with path ["book","rating"]
5 presentError: no code, has path -> message "internal server error", code INTERNAL_SERVER_ERROR
6 HTTP 200: { "data": {"book": {"title": "...", "rating": null}}, "errors": [ {...} ] }Real scenario: NOT_FOUND lets a client render a 404 view for one panel while the rest of the page works; BAD_USER_INPUT with the offending argument name drives form validation; UNAUTHENTICATED triggers a token refresh; a failing recommendations resolver degrades gracefully because its field is nullable.
| Error class | Raised by | Has path? | data | Typical extensions.code |
|---|---|---|---|---|
| Parse / validation | gqlparser before execution | No (has locations) | absent | GRAPHQL_PARSE_FAILED, GRAPHQL_VALIDATION_FAILED |
| Limit exceeded | Extension | No | absent | COMPLEXITY_LIMIT_EXCEEDED, DEPTH_LIMIT_EXCEEDED (ours) |
| Resolver error on a nullable field | Resolver | Yes | field null | Yours |
| Resolver error on a non-null field | Resolver | Yes | nearest nullable ancestor null | Yours |
| Panic | Resolver | Yes | as above | via SetRecoverFunc |
| Transport | HTTP layer | No | absent | none; HTTP 400 for bad JSON |
Fix / how to use it: define a small set of stable extensions.code values and document them as part of the API; map domain errors in one presenter; keep messages free of SQL or stack traces; log the original error server-side with the request id; make a field nullable when its failure should not take down its parent.
Pagination: Relay cursor connections Must-know
In plain words: Instead of "give me page 3", the client says "give me 10 items after this bookmark". Each item comes with its own bookmark (a cursor), and the page tells you whether another page exists.
Common misunderstanding: "A cursor is just an offset." Offsets break when rows are inserted while the user pages and make the database skip and discard N rows. A cursor is an opaque token that encodes a position in a stable order, here the primary key. The Relay specification says: "This cursor is an opaque string", and clients must not parse it.
Definition: the Relay connection shape: a field takes first/after (forward) or last/before (backward) and returns a connection with edges (each an edge with cursor and node) and pageInfo. The Relay spec says "PageInfo must contain fields hasPreviousPage and hasNextPage, both of which return non-null booleans. It must also contain fields startCursor and endCursor", so all four are in the schema even for forward-only paging (hasPreviousPage is true when an after cursor was given). The graphql.org pagination guide states why: "cursor-based pagination is the most powerful of those designed". This chapter's BookConnection implements forward paging with keyset logic: the server decodes the cursor to an id, asks for first + 1 rows with id > $after, and uses the extra row only to set hasNextPage (see Pagination: Offset vs Keyset).
query { books(first: 4) { pageInfo { hasNextPage hasPreviousPage startCursor endCursor } edges { node { id } } } }
1 Query.books(first:4, after:null) -> decodeCursor("") = ""
2 BooksPage("", "", 4): b1..b4, hasNext=true, total=6
3 startCursor = encode("b1"), endCursor = encode("b4") = "Ym9vazpiNA=="
4 next: books(first:4, after:"Ym9vazpiNA==") -> id > b4 -> b5, b6, hasNext=falsepackage graph
import (
"context"
"fmt"
"academy/graphql-in-go/graph/model"
)
// connection builds a Relay-style connection with keyset pagination. Helpers
// live outside schema.resolvers.go: gqlgen moves unknown code in that file
// into a comment block when it regenerates.
func (r *Resolver) connection(ctx context.Context, authorID string, first *int, after *string) (*model.BookConnection, error) {
n := 10
if first != nil {
n = *first
}
if n < 1 || n > 100 {
return nil, fmt.Errorf("first must be between 1 and 100: %w", ErrBadInput)
}
afterID := ""
if after != nil {
var err error
if afterID, err = decodeCursor(*after); err != nil {
return nil, fmt.Errorf("%w: %v", ErrBadInput, err)
}
}
page, hasNext, total, err := r.BookSvc.BooksPage(ctx, authorID, afterID, n)
if err != nil {
return nil, err
}
conn := &model.BookConnection{TotalCount: total, PageInfo: &model.PageInfo{HasNextPage: hasNext, HasPreviousPage: afterID != ""}}
for _, b := range page {
conn.Edges = append(conn.Edges, &model.BookEdge{Cursor: encodeCursor(b.ID), Node: b})
}
if len(conn.Edges) > 0 {
start, end := conn.Edges[0].Cursor, conn.Edges[len(conn.Edges)-1].Cursor
conn.PageInfo.StartCursor, conn.PageInfo.EndCursor = &start, &end
}
return conn, nil
}package graph
import (
"encoding/base64"
"fmt"
"strings"
)
const cursorPrefix = "book:"
// encodeCursor makes an opaque Relay cursor out of a primary key. Clients
// must treat it as a black box; the prefix lets the server reject garbage.
func encodeCursor(id string) string {
return base64.URLEncoding.EncodeToString([]byte(cursorPrefix + id))
}
// decodeCursor reverses encodeCursor; "" decodes to "" (first page).
func decodeCursor(c string) (string, error) {
if c == "" {
return "", nil
}
raw, err := base64.URLEncoding.DecodeString(c)
if err != nil || !strings.HasPrefix(string(raw), cursorPrefix) {
return "", fmt.Errorf("invalid cursor %q", c)
}
return strings.TrimPrefix(string(raw), cursorPrefix), nil
}-- keyset page behind books(first: 4, after: C), PostgreSQL
SELECT id, title, author_id FROM books
WHERE id > $1 -- decoded cursor; omit on the first page
ORDER BY id
LIMIT 5; -- first + 1: the extra row only sets hasNextPage
-- total count is a separate, often cached, query: SELECT count(*) FROM books;Real scenario: an infinite-scroll feed where new posts arrive while the user scrolls (offset would repeat or skip items); an admin table of millions of rows; a nested connection author.books(first: 3) loaded for ten authors (which is again an N+1 candidate, batched by author id).
| Approach | Stable under inserts | Cost at depth | Random page access |
|---|---|---|---|
limit/offset | No | Grows with the offset | Yes |
| Keyset (cursor = last key) | Yes | Constant (index seek) | No |
| Cursor = offset (opaque) | No | Grows | Yes |
| Relay connection over keyset | Yes | Constant | No |
Fix / how to use it: cap first (the chapter rejects values outside 1..100 with BAD_USER_INPUT), order by a unique column (add a tiebreaker for non-unique sort keys), reject malformed cursors, keep totalCount optional because it costs a count, and add a complexity function so first: 100 costs 100 times its children (limits).
Subscriptions over WebSockets Important
In plain words: A subscription is a query that never finishes: the client says "tell me whenever a book is added" and the server pushes a message each time, over one long-lived WebSocket connection.
Common misunderstanding: "Subscriptions give me durable messaging." They give you push to currently connected clients. An event published while the client is disconnected is gone, so the client must refetch state on reconnect. And an in-process broker, as here, only reaches subscribers on the same replica.
Definition: a subscription root field whose resolver returns a channel; gqlgen reads from it until the channel closes or ctx is cancelled (client sent "complete" or disconnected) and executes the selection set for each value. The transport is transport.Websocket, which in v0.17.86 embeds a gorilla/websocket Upgrader and speaks both the legacy graphql-ws and the newer graphql-transport-ws subprotocols (the latter documented in the graphql-ws PROTOCOL.md). Two practical rules from the gqlgen recipe: register the WebSocket transport first ("Add WebSocket first"), and "remember to send ALL requests go to your handler (at /query), not just POST requests!".
package store
import (
"context"
"sync"
"academy/graphql-in-go/graph/model"
)
// Broker is an in-process pub/sub used by the bookAdded subscription. A real
// deployment replaces it with Redis, NATS or Kafka so every replica sees
// every event; the resolver code does not change.
type Broker struct {
mu sync.Mutex
subs map[chan *model.Book]struct{}
}
// NewBroker returns an empty broker.
func NewBroker() *Broker { return &Broker{subs: map[chan *model.Book]struct{}{}} }
// Publish never blocks: a slow subscriber loses events instead of stalling
// the mutation (the buffer is 8).
func (b *Broker) Publish(book *model.Book) {
b.mu.Lock()
defer b.mu.Unlock()
for ch := range b.subs {
select {
case ch <- book:
default:
}
}
}
// Subscribe registers a subscriber and unregisters it when ctx ends, which
// gqlgen cancels when the client disconnects or sends "complete".
func (b *Broker) Subscribe(ctx context.Context) <-chan *model.Book {
ch := make(chan *model.Book, 8)
b.mu.Lock()
b.subs[ch] = struct{}{}
b.mu.Unlock()
go func() {
<-ctx.Done()
b.mu.Lock()
delete(b.subs, ch)
b.mu.Unlock()
close(ch)
}()
return ch
}
// Subscribers reports how many subscriptions are live (used by tests).
func (b *Broker) Subscribers() int {
b.mu.Lock()
defer b.mu.Unlock()
return len(b.subs)
}client server (replica A)
1 Upgrade: websocket ----------------> transport.Websocket upgrades (CheckOrigin!)
2 connection_init -------------------> InitFunc may authenticate; connection_ack <-
3 subscribe {bookAdded{title}} ------> resolver: Events.Subscribe(ctx) -> channel
4 mutation addBook on A -> Events.Publish(book)
5 <------------------ next {title:"Live"} gqlgen runs the selection set per event
6 complete / close ------------------> ctx cancelled -> broker unsubscribesReal scenario: a collaborative document showing "3 people are viewing"; an order-status page updated as the warehouse scans items; a live auction. For fan-out across replicas, publish to Redis, NATS or Kafka and subscribe in the resolver (Event-Driven Go); for the transport trade-offs see Real-Time Communication.
| Concern | Rule |
|---|---|
| Origin check | Upgrader.CheckOrigin must validate against an allow-list; the demo returns true |
| Auth | Browsers cannot set headers on a WebSocket: authenticate in InitFunc from the connection_init payload, or by cookie |
| Backpressure | Never block Publish; here a slow subscriber loses events (buffer of 8) |
| Keep-alive | KeepAlivePingInterval (10 s here) keeps proxies from closing idle sockets |
| Scaling | Sticky sessions are not needed if every replica subscribes to the shared bus |
| Cleanup | Unsubscribe on ctx.Done() or you leak goroutines and channels |
Fix / how to use it: keep subscription payloads small (send the id and let the client refetch, or send the fields it selected), cap the number of subscriptions per connection, and test with client.Websocket (see Testing). Server-sent events are the simpler alternative for one-way streams; gqlgen v0.17.86 ships transport.SSE.
Query complexity and depth limits Must-know
In plain words: Because clients write the query, one client can write a query that costs a thousand times more than another. You give each field a price, add them up before running anything, and refuse queries over budget. Depth limiting is the simpler cousin: refuse queries nested more than N levels.
Common misunderstanding: "My resolvers are fast, so I do not need limits." The cost is not in one resolver, it is in the multiplication: books(first: 100) { author { books(first: 100) { author { ... } } } } grows exponentially with each level. The gqlgen docs: "The size of the response grows exponentially with each additional level".
Definition: gqlgen's extension.FixedComplexityLimit(n) rejects an operation whose computed complexity exceeds n. "By default, each field and level of depth adds one to the overall query complexity." You then give list fields a custom function through Config.Complexity.<Type>.<Field>, whose signature includes childComplexity and the field's arguments: return first * childComplexity. extension.ComplexityLimit computes the limit per request. gqlgen v0.17.86 ships no depth limit, so limits.Depth below is this chapter's own graphql.OperationContextMutator; OWASP lists the same defence: "Add depth limiting to incoming queries".
// Package limits holds the query-shape guards gqlgen does not ship: a depth
// limit. (Complexity limiting is built in: extension.FixedComplexityLimit.)
package limits
import (
"context"
"fmt"
"github.com/99designs/gqlgen/graphql"
"github.com/vektah/gqlparser/v2/ast"
"github.com/vektah/gqlparser/v2/gqlerror"
)
// Depth rejects operations nested deeper than Max selection levels.
type Depth struct{ Max int }
var _ interface {
graphql.OperationContextMutator
graphql.HandlerExtension
} = Depth{}
// ExtensionName implements graphql.HandlerExtension.
func (Depth) ExtensionName() string { return "DepthLimit" }
// Validate implements graphql.HandlerExtension.
func (Depth) Validate(graphql.ExecutableSchema) error { return nil }
// MutateOperationContext runs after parsing and validation, before execution.
func (d Depth) MutateOperationContext(_ context.Context, oc *graphql.OperationContext) *gqlerror.Error {
got := selectionDepth(oc.Operation.SelectionSet, 0)
if got > d.Max {
return &gqlerror.Error{
Message: fmt.Sprintf("operation has depth %d, which exceeds the limit of %d", got, d.Max),
Extensions: map[string]any{"code": "DEPTH_LIMIT_EXCEEDED"},
}
}
return nil
}
// selectionDepth returns the deepest nesting of fields below set. Fragment
// spreads and inline fragments do not add a level; the fields they contain do.
// Validation has already rejected fragment cycles.
func selectionDepth(set ast.SelectionSet, level int) int {
deepest := level
for _, sel := range set {
var d int
switch s := sel.(type) {
case *ast.Field:
d = selectionDepth(s.SelectionSet, level+1)
case *ast.InlineFragment:
d = selectionDepth(s.SelectionSet, level)
case *ast.FragmentSpread:
d = selectionDepth(s.Definition.SelectionSet, level)
}
deepest = max(deepest, d)
}
return deepest
}{ books(first: 100) { edges { node { title } } } } limit 20
1 complexity = pageSize(100) x child(books > edges > node > title = 3) = 300
2 300 > 20 -> reject BEFORE any resolver runs
3 { "errors": [ { "message": "operation has complexity 300, which exceeds the limit of 20",
4 "extensions": { "code": "COMPLEXITY_LIMIT_EXCEEDED" } } ] } HTTP 200Real scenario: a public API where anonymous clients get a limit of 100 and authenticated partners 1000 (via ComplexityLimit with a per-request function); an alias flood { a: books(first:100){...} b: books(first:100){...} ... } that depth limiting alone would not stop but complexity does; a nested author { books { author { books } } } cycle stopped by depth.
| Technique | Stops | Misses |
|---|---|---|
| Depth limit | Cycles such as a { b { a { b ... | Wide, shallow, expensive queries |
| Complexity limit with list multipliers | Wide queries, alias floods | Cheap-looking fields that are slow |
Page-size cap (first between 1 and 100) | Unbounded lists | Many small pages in a loop (rate limit) |
Timeout via ctx | Slow resolvers | Cheap-to-start, expensive-to-finish work already done |
| Persisted-query allow-list | Everything not pre-approved | Operational friction for new queries |
Fix / how to use it: apply all three of page-size cap, complexity limit and depth limit, then monitor graphql.GetOperationContext(ctx).Stats and rejected-query counts to tune them; combine with HTTP rate limiting (Rate Limiting in Go) because one request's cost and the number of requests are separate dimensions.
Introspection in production, and the playground Important
In plain words: Introspection lets a client ask the server "what is your schema?". It powers the autocomplete in tools. In production it hands attackers a map of everything you expose, so you normally turn it off.
Common misunderstanding: "Disabling introspection secures the API." It removes the convenient map, but a guessed field name still works and error messages with "Did you mean ...?" suggestions can leak names. Security still needs authorization and limits. OWASP is still unambiguous: "Disable introspection queries system-wide in any production or publicly accessible environments."
Definition: in gqlgen introspection is off until you add extension.Introspection{}; the docs show guarding it by environment or per request (DisableIntrospection = true on the operation context for non-admins). The GraphQL playground is a browser IDE served by playground.Handler(title, endpoint); it needs introspection to autocomplete. The server in this chapter installs both only when Config.Production is false and turns on SetDisableSuggestion(true) in production.
query { __schema { queryType { name } } }
dev (Introspection installed) -> { "data": { "__schema": { "queryType": { "name": "Query" } } } }
prod (not installed) -> { "errors": [ { "message": "introspection disabled", "path": ["__schema"] } ] }
GET /playground: dev 200, prod 404 (not mounted)Real scenario: a public API where the docs site is generated from a schema file checked into the repo (so introspection is not needed); an internal API behind a VPN where introspection stays on for tooling; a partner API where only authenticated admins may introspect.
| Environment | Introspection | Playground | Suggestions |
|---|---|---|---|
| Development | On | On | On |
| Staging | On, behind auth | Optional | On |
| Production, public | Off | Not mounted | Off |
| Production, internal | On for admins | Not mounted | Off |
Fix / how to use it: tie the switches to one Config.Production flag as server.New does, test the production configuration (TestIntrospectionOffInProduction), and publish the schema file as the documentation instead.
Persisted queries (APQ) Important
In plain words: Instead of sending the whole query text on every request, the client sends a short fingerprint of it. If the server has seen the query before it runs it; if not it says "I do not know that one", and the client sends the full text once.
Common misunderstanding: "APQ is a security feature." Automatic persisted queries are a bandwidth and caching optimisation: any client can register any query. A real allow-list of persisted queries (only hashes registered at build time are accepted) is the security feature, and gqlgen's APQ extension does not enforce one by itself. Apollo describes APQ as: "A persisted query is a query string that's cached on the server side, along with its unique identifier (always its SHA-256 hash)."
Definition: the client sends extensions.persistedQuery = { version: 1, sha256Hash: ... }. gqlgen's extension.AutomaticPersistedQuery{Cache: ...} takes a graphql.Cache[string]; the chapter uses lru.New[string](100) from github.com/99designs/gqlgen/graphql/handler/lru, and a Redis-backed cache is the production choice so all replicas share it. A hash-only request for an unknown hash fails with PersistedQueryNotFound (code PERSISTED_QUERY_NOT_FOUND); a request with both text and hash is verified ("provided APQ hash does not match query" if wrong) and stored.
1 client -> { extensions: { persistedQuery: { version: 1, sha256Hash: H } } }
2 server: cache miss -> errors: [ { message: "PersistedQueryNotFound" } ] HTTP 200
3 client -> { query: "{ book(id: \"b1\") { title } }", extensions: { ...H } }
4 server: sha256(query) == H -> store, execute
5 client -> { extensions: { ...H } } (every later request)
6 server: cache hit -> executeReal scenario: a mobile app on a slow network sending 4 KB queries 50 times a minute; a CDN that can cache GET /query?extensions=...&variables=... because the URL is short and stable; a locked-down partner API that accepts only the 30 hashes registered at deploy time.
| Feature | Automatic persisted queries | Persisted-query allow-list |
|---|---|---|
| Registration | At run time by any client | At build/deploy time |
| Purpose | Smaller requests, GET and CDN caching | Security, predictable load |
| Unknown query | Registers it | Rejects it |
| gqlgen | extension.AutomaticPersistedQuery | Your own MutateOperationParameters extension |
| Needs shared cache | Yes, across replicas | Yes, or a static map |
Fix / how to use it: share the cache across replicas, size the LRU by the number of distinct queries, remember GET requests must be idempotent queries only, and add an allow-list if you need to refuse unknown queries.
Batching Good to know
In plain words: "Batching" means three different things in GraphQL, and mixing them up causes confusion. The server batches database lookups (dataloaders). A client can batch several operations into one HTTP request. And a client can batch many aliased fields into one operation.
Common misunderstanding: "gqlgen supports sending an array of queries in one request." Not in v0.17.86: the HTTP POST transport has no array-batching mode (a search of its transport package found batching only in the multipart-mixed transport, which is incremental delivery, not an array of operations). If you need it, put a batching layer in front of the server. Be wary: OWASP describes query batching as letting "callers to either batch multiple queries or batch requests for multiple object instances in a single network call", which "allows for what is called a batching attack", a GraphQL-specific form of brute force: ten login attempts in one request defeat per-request rate limits.
Definition: (1) dataloader batching: many Load calls become one query (Dataloaders). (2) Operation batching: a JSON array of operations in one POST, supported by some servers and gateways, not by gqlgen's POST transport. (3) Alias batching: { a: login(...) b: login(...) } runs the same field many times in one operation, which is legal GraphQL (aliases are part of the spec) and the reason limits must count work, not requests.
{ a: login(u: "x", p: "1") b: login(u: "x", p: "2") c: login(u: "x", p: "3") }
1 one HTTP request, one rate-limit tick
2 three password guesses
3 fix: complexity cost per login field, or a per-field rate limiter keyed by userReal scenario: a brute-force attempt against login using 100 aliases; a dashboard issuing 12 independent queries that a gateway merges into one round trip; a resolver graph where 40 author lookups become one query.
| Kind | Where | Helps | Risk |
|---|---|---|---|
| Dataloader | Server resolvers | Database round trips | Stale cache if shared across requests |
| Operation array | Client plus gateway | Network round trips | Bypasses per-request limits |
| Aliases | Query text | Fewer requests | Rate-limit bypass, cost amplification |
Fix / how to use it: count aliases and fields in your complexity function, rate-limit sensitive mutations by identity (not by request), and cap the number of operations if you add array batching.
Tracing with OpenTelemetry Good to know
In plain words: Tracing records how long each part of a request took, as a tree: the operation at the top, each slow resolver below it. When a query is slow you can see which field is to blame.
Common misunderstanding: "Trace every field." Fields that just read a struct field take nanoseconds, and a span for each drowns the useful ones; trace the fields that have resolvers.
Definition: gqlgen exposes two interception points as handler extensions: graphql.OperationInterceptor (around the whole operation) and graphql.FieldInterceptor (around each field). The v0.17.86 tree also contains apollotracing and apollofederatedtracingv1 handler packages for Apollo's formats. The OpenTelemetry extension below is this chapter's own (about 70 lines): one span per operation, one child span per field where graphql.GetFieldContext(ctx).IsResolver, errors recorded on the span. dataloadgen has WithTracer for spans around batches.
// Package tracing is a small OpenTelemetry extension for gqlgen: one span per
// operation and one child span per field that runs a resolver. Trivial fields
// (a struct field read) get no span, or traces drown in noise.
package tracing
import (
"context"
"github.com/99designs/gqlgen/graphql"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
)
// Extension implements graphql.HandlerExtension plus the two interceptors.
type Extension struct{ Tracer trace.Tracer }
var _ interface {
graphql.HandlerExtension
graphql.OperationInterceptor
graphql.FieldInterceptor
} = Extension{}
// ExtensionName implements graphql.HandlerExtension.
func (Extension) ExtensionName() string { return "OpenTelemetryTracing" }
// Validate implements graphql.HandlerExtension.
func (Extension) Validate(graphql.ExecutableSchema) error { return nil }
// InterceptOperation wraps the whole operation (parse, validate, execute).
func (e Extension) InterceptOperation(ctx context.Context, next graphql.OperationHandler) graphql.ResponseHandler {
if !graphql.HasOperationContext(ctx) {
return next(ctx)
}
oc := graphql.GetOperationContext(ctx)
name := oc.OperationName
if name == "" && oc.Operation != nil {
name = oc.Operation.Name // the name written in the query text
}
if name == "" {
name = "anonymous"
}
ctx, span := e.Tracer.Start(ctx, "graphql.operation "+name, trace.WithAttributes(
attribute.String("graphql.operation.name", name),
))
handler := next(ctx)
return func(ctx context.Context) *graphql.Response {
defer span.End()
resp := handler(ctx)
if resp != nil && len(resp.Errors) > 0 {
span.SetStatus(codes.Error, resp.Errors[0].Message)
}
return resp
}
}
// InterceptField runs around every field; only resolver fields get a span.
func (e Extension) InterceptField(ctx context.Context, next graphql.Resolver) (any, error) {
fc := graphql.GetFieldContext(ctx)
if !fc.IsResolver {
return next(ctx)
}
ctx, span := e.Tracer.Start(ctx, "graphql.field "+fc.Object+"."+fc.Field.Name)
defer span.End()
res, err := next(ctx)
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
}
return res, err
}operation Shelf (span)
1 Query.books 0.4 ms
2 Book.author x2 (children of 1) batch wait 2 ms, then 1 fetch
3 errors on the response mark the operation span: status ErrorReal scenario: finding that Book.rating takes 300 ms because the ratings service is slow, and fixing it with a loader plus a timeout; correlating a slow GraphQL operation with the database spans below it via the propagated ctx.
| Span | Name pattern | Attributes |
|---|---|---|
| Operation | graphql.operation <name> | graphql.operation.name |
| Field | graphql.field Type.field | Error status on failure |
| Batch (dataloadgen) | Library-defined | Batch size |
Fix / how to use it: name your operations in the client (anonymous operations are impossible to find in traces), install the extension once with srv.Use, and export with the standard OpenTelemetry SDK.
Testing: client.New and httptest Must-know
In plain words: You can test the whole GraphQL stack without opening a port: build the handler, send it a query in memory, and read the JSON back. Because the data layer is behind interfaces, the test also controls the database.
Common misunderstanding: "Resolver unit tests are enough." Unit tests miss the parts that fail in production: nullability propagation, directives, the error presenter, extensions, dataloader batching and the real JSON shape. Test through the handler.
Definition: gqlgen ships a small client, github.com/99designs/gqlgen/client: client.New(h http.Handler, opts...) then Post, RawPost and Websocket. Its own README says "This client is used internally for testing." Options: client.Var, client.Path, client.AddHeader, client.Operation. Post unpacks into your struct and returns a client.RawJsonError when the response has errors; RawPost returns Data and the raw Errors so you can assert partial responses. For raw HTTP details (status codes, APQ) use httptest.NewRecorder directly.
func newEnv(cfg server.Config) *env {
db, ev := store.NewMemory(), store.NewBroker()
h := server.New(cfg, db, ev) // the real handler tree
return &env{h: h, db: db, ev: ev, c: client.New(h, client.Path("/query"))}
}package server_test
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"academy/graphql-in-go/graph/model"
"academy/graphql-in-go/server"
"academy/graphql-in-go/store"
"github.com/99designs/gqlgen/client"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/sdk/trace/tracetest"
)
// spyStore is a different implementation of the service interfaces: it
// wraps the in-memory store and counts every call that reaches it. Passing it
// to server.New is also the compile-time proof that New takes interfaces.
type spyStore struct {
*store.Memory
calls atomic.Int64
}
var _ server.Services = (*spyStore)(nil)
func (s *spyStore) AuthorByID(ctx context.Context, id string) (*model.Author, error) {
s.calls.Add(1)
return s.Memory.AuthorByID(ctx, id)
}
func (s *spyStore) AuthorsByIDs(ctx context.Context, ids []string) ([]*model.Author, error) {
s.calls.Add(1)
return s.Memory.AuthorsByIDs(ctx, ids)
}
func (s *spyStore) SearchAuthors(ctx context.Context, t string) ([]*model.Author, error) {
s.calls.Add(1)
return s.Memory.SearchAuthors(ctx, t)
}
func (s *spyStore) BookByID(ctx context.Context, id string) (*model.Book, error) {
s.calls.Add(1)
return s.Memory.BookByID(ctx, id)
}
func (s *spyStore) BooksPage(ctx context.Context, a, after string, n int) ([]*model.Book, bool, int, error) {
s.calls.Add(1)
return s.Memory.BooksPage(ctx, a, after, n)
}
func (s *spyStore) SearchBooks(ctx context.Context, t string) ([]*model.Book, error) {
s.calls.Add(1)
return s.Memory.SearchBooks(ctx, t)
}
func (s *spyStore) AddBook(ctx context.Context, in model.NewBook) (*model.Book, error) {
s.calls.Add(1)
return s.Memory.AddBook(ctx, in)
}
func (s *spyStore) Rating(ctx context.Context, id string) (float64, error) {
s.calls.Add(1)
return s.Memory.Rating(ctx, id)
}
// newSpyEnv builds the server on top of the spy instead of *store.Memory.
func newSpyEnv(cfg server.Config) (*env, *spyStore) {
spy := &spyStore{Memory: store.NewMemory()}
ev := store.NewBroker()
h := server.New(cfg, spy, ev)
return &env{h: h, db: spy.Memory, ev: ev, c: client.New(h, client.Path("/query"))}, spy
}
// env bundles a handler with the fakes behind it so tests can inspect them.
type env struct {
h http.Handler
db *store.Memory
ev *store.Broker
c *client.Client
}
func newEnv(cfg server.Config) *env {
db, ev := store.NewMemory(), store.NewBroker()
h := server.New(cfg, db, ev)
return &env{h: h, db: db, ev: ev, c: client.New(h, client.Path("/query"))}
}
// gqlError is the shape of one entry of the response's "errors" array.
type gqlError struct {
Message string `json:"message"`
Path []any `json:"path"`
Extensions map[string]any `json:"extensions"`
}
// run executes a query and returns data and errors separately, because in
// GraphQL both can be present at once (a partial response).
func (e *env) run(t *testing.T, query string, opts ...client.Option) (map[string]any, []gqlError) {
t.Helper()
resp, err := e.c.RawPost(query, opts...)
if err != nil {
t.Fatalf("transport error: %v", err)
}
var errs []gqlError
if resp.Errors != nil {
if err := json.Unmarshal(resp.Errors, &errs); err != nil {
t.Fatal(err)
}
}
data, _ := resp.Data.(map[string]any)
return data, errs
}
func role(r string) client.Option { return client.AddHeader("X-Demo-Role", r) }
func code(e gqlError) any { return e.Extensions["code"] }
func TestPartialResponse(t *testing.T) {
e := newEnv(server.Config{})
data, errs := e.run(t, `{ book(id: "b3") { title rating } }`)
book := data["book"].(map[string]any)
if book["title"] != "Go To Considered" || book["rating"] != nil {
t.Fatalf("book = %v, want title set and rating null", book)
}
if len(errs) != 1 || strings.Join(toStrings(errs[0].Path), ".") != "book.rating" {
t.Fatalf("errors = %+v, want one error at book.rating", errs)
}
if code(errs[0]) != "INTERNAL_SERVER_ERROR" || errs[0].Message != "internal server error" {
t.Fatalf("internal details leaked: %+v", errs[0])
}
}
func TestNotFoundCode(t *testing.T) {
e := newEnv(server.Config{})
data, errs := e.run(t, `{ book(id: "nope") { title } }`)
if data["book"] != nil || len(errs) != 1 || code(errs[0]) != "NOT_FOUND" {
t.Fatalf("data=%v errs=%+v", data, errs)
}
}
func TestDataloaderBatchesAuthors(t *testing.T) {
e := newEnv(server.Config{})
data, errs := e.run(t, `{ books(first: 6) { totalCount edges { node { title author { name } } } } }`)
if len(errs) != 0 {
t.Fatalf("errors: %+v", errs)
}
edges := data["books"].(map[string]any)["edges"].([]any)
if len(edges) != 6 {
t.Fatalf("edges = %d", len(edges))
}
st := e.db.Stats()
if st.BookQueries != 1 || st.AuthorQueries != 1 {
t.Fatalf("stats = %+v, want 1 book query and ONE batched author query", st)
}
}
// Relay requires all four PageInfo fields, even for forward-only paging.
func TestPageInfoHasAllRelayFields(t *testing.T) {
e := newEnv(server.Config{})
const q = `query($after: String) { books(first: 2, after: $after) {
pageInfo { hasNextPage hasPreviousPage startCursor endCursor } edges { cursor } } }`
data, errs := e.run(t, q)
if len(errs) != 0 {
t.Fatalf("errors = %+v", errs)
}
conn := data["books"].(map[string]any)
pi := conn["pageInfo"].(map[string]any)
first := conn["edges"].([]any)[0].(map[string]any)["cursor"]
if pi["hasPreviousPage"] != false || pi["startCursor"] != first || pi["hasNextPage"] != true {
t.Fatalf("page 1 pageInfo = %v", pi)
}
data, _ = e.run(t, q, client.Var("after", pi["endCursor"]))
pi = data["books"].(map[string]any)["pageInfo"].(map[string]any)
if pi["hasPreviousPage"] != true {
t.Fatalf("page 2 pageInfo = %v", pi)
}
}
func TestRelayPagination(t *testing.T) {
e := newEnv(server.Config{})
const q = `query($after: String) { books(first: 4, after: $after) {
totalCount pageInfo { hasNextPage endCursor } edges { cursor node { id } } } }`
data, _ := e.run(t, q)
conn := data["books"].(map[string]any)
pi := conn["pageInfo"].(map[string]any)
if pi["hasNextPage"] != true || len(conn["edges"].([]any)) != 4 || conn["totalCount"].(float64) != 6 {
t.Fatalf("page 1 = %v", conn)
}
data, _ = e.run(t, q, client.Var("after", pi["endCursor"]))
conn = data["books"].(map[string]any)
edges := conn["edges"].([]any)
first := edges[0].(map[string]any)["node"].(map[string]any)["id"]
if len(edges) != 2 || first != "b5" || conn["pageInfo"].(map[string]any)["hasNextPage"] != false {
t.Fatalf("page 2 = %v", conn)
}
_, errs := e.run(t, q, client.Var("after", "not-a-cursor"))
if len(errs) != 1 || code(errs[0]) != "BAD_USER_INPUT" {
t.Fatalf("bad cursor errors = %+v", errs)
}
}
func TestAuthDirective(t *testing.T) {
e := newEnv(server.Config{})
const q = `{ secretShelf { title } }`
_, errs := e.run(t, q)
if len(errs) != 1 || code(errs[0]) != "UNAUTHENTICATED" {
t.Fatalf("anonymous: %+v", errs)
}
data, errs := e.run(t, q, role("READER"))
if len(errs) != 0 || len(data["secretShelf"].([]any)) != 6 {
t.Fatalf("reader: %v %+v", data, errs)
}
const m = `mutation { addBook(input: {title: "New", authorId: "a1", tags: ["x"]}) { id title } }`
_, errs = e.run(t, m, role("READER"))
if len(errs) != 1 || code(errs[0]) != "FORBIDDEN" {
t.Fatalf("reader mutation: %+v", errs)
}
data, errs = e.run(t, m, role("EDITOR"))
if len(errs) != 0 || data["addBook"].(map[string]any)["id"] != "b7" {
t.Fatalf("editor mutation: %v %+v", data, errs)
}
}
func TestCustomScalars(t *testing.T) {
e := newEnv(server.Config{})
data, errs := e.run(t, `{ book(id: "b1") { externalId publishedAt } }`)
if len(errs) != 0 {
t.Fatal(errs)
}
b := data["book"].(map[string]any)
if len(b["externalId"].(string)) != 36 {
t.Fatalf("externalId = %v", b["externalId"])
}
if _, err := time.Parse(time.RFC3339Nano, b["publishedAt"].(string)); err != nil {
t.Fatalf("publishedAt = %v: %v", b["publishedAt"], err)
}
}
func TestUnionSearch(t *testing.T) {
e := newEnv(server.Config{})
data, errs := e.run(t, `{ search(term: "ada") { __typename ... on Author { name } ... on Book { title } } }`)
if len(errs) != 0 {
t.Fatal(errs)
}
got := data["search"].([]any)
if len(got) != 1 || got[0].(map[string]any)["__typename"] != "Author" {
t.Fatalf("search = %v", got)
}
}
func TestComplexityLimit(t *testing.T) {
e, spy := newSpyEnv(server.Config{ComplexityLimit: 20})
_, errs := e.run(t, `{ books(first: 100) { edges { node { title } } } }`)
if len(errs) != 1 || code(errs[0]) != "COMPLEXITY_LIMIT_EXCEEDED" {
t.Fatalf("errors = %+v", errs)
}
if n := spy.calls.Load(); n != 0 {
t.Fatalf("rejected query reached the services %d times", n)
}
t.Log(errs[0].Message)
data, errs := e.run(t, `{ books(first: 2) { edges { node { title } } } }`)
if len(errs) != 0 || data["books"] == nil {
t.Fatalf("small query rejected: %+v", errs)
}
}
func TestDepthLimit(t *testing.T) {
e, spy := newSpyEnv(server.Config{DepthLimit: 4})
deep := `{ books(first: 1) { edges { node { author { books(first: 1) { edges { node { title } } } } } } } }`
_, errs := e.run(t, deep)
if len(errs) != 1 || code(errs[0]) != "DEPTH_LIMIT_EXCEEDED" {
t.Fatalf("errors = %+v", errs)
}
if n := spy.calls.Load(); n != 0 {
t.Fatalf("rejected query reached the services %d times", n)
}
t.Log(errs[0].Message)
_, errs = e.run(t, `{ books(first: 1) { edges { node { title } } } }`)
if len(errs) != 0 {
t.Fatalf("depth-4 query rejected: %+v", errs)
}
}
func TestIntrospectionOffInProduction(t *testing.T) {
const q = `{ __schema { queryType { name } } }`
dev := newEnv(server.Config{})
data, errs := dev.run(t, q)
if len(errs) != 0 || data["__schema"] == nil {
t.Fatalf("dev: %v %+v", data, errs)
}
prod := newEnv(server.Config{Production: true})
_, errs = prod.run(t, q)
if len(errs) != 1 {
t.Fatalf("prod errors = %+v", errs)
}
t.Logf("%+v", errs[0])
// The playground is not mounted in production either.
rec := httptest.NewRecorder()
prod.h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/playground", nil))
if rec.Code != http.StatusNotFound {
t.Fatalf("playground in production: %d", rec.Code)
}
rec = httptest.NewRecorder()
dev.h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/playground", nil))
if rec.Code != http.StatusOK {
t.Fatalf("playground in dev: %d", rec.Code)
}
}
func TestAutomaticPersistedQueries(t *testing.T) {
e := newEnv(server.Config{})
const query = `{ book(id: "b1") { title } }`
post := func(body string) string {
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/query", bytes.NewBufferString(body))
req.Header.Set("Content-Type", "application/json")
e.h.ServeHTTP(rec, req)
return rec.Body.String()
}
h := sha256Hex(query) // what an APQ client computes
ext := `"extensions":{"persistedQuery":{"version":1,"sha256Hash":"` + h + `"}}`
if got := post(`{` + ext + `}`); !strings.Contains(got, "PersistedQueryNotFound") {
t.Fatalf("first hash-only request: %s", got)
}
qj, _ := json.Marshal(query)
if got := post(`{"query":` + string(qj) + `,` + ext + `}`); !strings.Contains(got, `"title":"Notes"`) {
t.Fatalf("registering request: %s", got)
}
if got := post(`{` + ext + `}`); !strings.Contains(got, `"title":"Notes"`) {
t.Fatalf("hash-only request after registration: %s", got)
}
}
func TestSubscriptionOverWebSocket(t *testing.T) {
e := newEnv(server.Config{})
sub := e.c.Websocket(`subscription { bookAdded { id title } }`)
defer sub.Close()
// The subscription registers asynchronously after the handshake.
deadline := time.Now().Add(2 * time.Second)
for e.ev.Subscribers() == 0 {
if time.Now().After(deadline) {
t.Fatal("subscription never registered")
}
time.Sleep(5 * time.Millisecond)
}
_, errs := e.run(t, `mutation { addBook(input: {title: "Live", authorId: "a2"}) { id } }`, role("EDITOR"))
if len(errs) != 0 {
t.Fatal(errs)
}
var msg struct {
BookAdded struct{ ID, Title string }
}
if err := sub.Next(&msg); err != nil {
t.Fatal(err)
}
if msg.BookAdded.Title != "Live" {
t.Fatalf("event = %+v", msg)
}
}
func toStrings(p []any) []string {
out := make([]string, len(p))
for i, v := range p {
out[i], _ = v.(string)
}
return out
}
func TestOpenTelemetrySpans(t *testing.T) {
exp := tracetest.NewInMemoryExporter()
tp := sdktrace.NewTracerProvider(sdktrace.WithSyncer(exp))
e := newEnv(server.Config{Tracer: tp.Tracer("graphql-test")})
_, errs := e.run(t, `query Shelf { books(first: 2) { edges { node { title author { name } } } } }`)
if len(errs) != 0 {
t.Fatal(errs)
}
names := map[string]int{}
for _, s := range exp.GetSpans() {
names[s.Name]++
}
// One operation span, one Query.books span, one Book.author span per book.
if names["graphql.operation Shelf"] != 1 || names["graphql.field Query.books"] != 1 || names["graphql.field Book.author"] != 2 {
t.Fatalf("spans = %v", names)
}
if names["graphql.field Book.title"] != 0 {
t.Fatalf("trivial field got a span: %v", names)
}
}
// TestStatusCodes records which HTTP status gqlgen v0.17.86 uses for each
// failure class. The GraphQL-over-HTTP draft says a server SHOULD answer 200
// for execution errors; request errors differ between servers.
func TestStatusCodes(t *testing.T) {
e := newEnv(server.Config{ComplexityLimit: 20, DepthLimit: 4})
post := func(body string) (int, string) {
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/query", bytes.NewBufferString(body))
req.Header.Set("Content-Type", "application/json")
e.h.ServeHTTP(rec, req)
return rec.Code, rec.Body.String()
}
cases := []struct {
name, body string
want int
}{
{"ok", `{"query":"{ book(id: \"b1\") { title } }"}`, http.StatusOK},
{"resolver error", `{"query":"{ book(id: \"zzz\") { title } }"}`, http.StatusOK},
{"syntax error", `{"query":"{ book(id: "}`, http.StatusUnprocessableEntity},
{"unknown field", `{"query":"{ nope }"}`, http.StatusUnprocessableEntity},
{"complexity limit", `{"query":"{ books(first: 100) { edges { node { title } } } }"}`, http.StatusOK},
{"depth limit", `{"query":"{ books(first: 1) { edges { node { author { name } } } } }"}`, http.StatusOK},
{"persisted hash unknown", `{"extensions":{"persistedQuery":{"version":1,"sha256Hash":"00"}}}`, http.StatusOK},
{"malformed JSON", `{`, http.StatusBadRequest},
}
for _, tc := range cases {
code, body := post(tc.body)
t.Logf("%-24s %d %.90s", tc.name, code, body)
if code != tc.want {
t.Errorf("%s: status %d, want %d", tc.name, code, tc.want)
}
}
}
// TestGraphQLResponseJSON shows gqlgen's content negotiation: with
// Accept: application/graphql-response+json it uses that media type and the
// status rules of the GraphQL-over-HTTP draft.
func TestGraphQLResponseJSON(t *testing.T) {
e := newEnv(server.Config{})
do := func(accept, body string) (int, string) {
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/query", bytes.NewBufferString(body))
req.Header.Set("Content-Type", "application/json")
if accept != "" {
req.Header.Set("Accept", accept)
}
e.h.ServeHTTP(rec, req)
return rec.Code, rec.Header().Get("Content-Type")
}
const bad = `{"query":"{ nope }"}`
if code, ct := do("", bad); code != 422 || !strings.HasPrefix(ct, "application/json") {
t.Fatalf("no Accept: %d %s", code, ct)
}
code, ct := do("application/graphql-response+json", bad)
t.Logf("graphql-response+json: %d %s", code, ct)
if !strings.HasPrefix(ct, "application/graphql-response+json") || code != http.StatusBadRequest {
t.Fatalf("negotiated: %d %s, want 400 and the graphql-response+json type", code, ct)
}
if code, _ := do("application/graphql-response+json", `{"query":"{ book(id: \"b1\") { title } }"}`); code != 200 {
t.Fatalf("valid query: %d", code)
}
}Real scenario: a pull request that adds a field breaks the N+1 guarantee: TestDataloaderBatchesAuthors fails because author queries become 6. A new directive is added and the test for the anonymous caller fails. A load test replaces the fake store with a counter.
| Test | Asserts | Why it exists |
|---|---|---|
TestPartialResponse | title set, rating null, one error at book.rating, message hidden | Spec behaviour and the presenter |
TestDataloaderBatchesAuthors | One author query for six books | Guards N+1 |
TestRelayPagination | Two pages, hasNextPage, bad cursor code | Cursor contract |
TestAuthDirective | UNAUTHENTICATED, FORBIDDEN, success | Directive wiring |
TestComplexityLimit, TestDepthLimit | Rejection code, and a spy store counts zero service calls for the rejected query | Limits stop work before execution |
TestPageInfoHasAllRelayFields | hasNextPage, hasPreviousPage, startCursor, endCursor | Relay spec requires all four |
TestIntrospectionOffInProduction | Error and 404 playground in production | Config flag |
TestAutomaticPersistedQueries | Not found, register, hit | APQ flow |
TestSubscriptionOverWebSocket | A mutation reaches the subscriber | Transport and broker |
TestOpenTelemetrySpans | Span names and counts | Tracing |
TestStatusCodes | 200, 400, 422 per failure class | HTTP behaviour |
TestGraphQLResponseJSON | Accept: application/graphql-response+json switches the media type and the status to 400 | Content negotiation |
Fix / how to use it: build the handler exactly as main does (one constructor), inject fakes through the Resolver interfaces, assert query counts, and run with -race -count=N (the repository's runs used -count=30 to check the batching tests are not timing-flaky). See Testing & Benchmarking for table-driven structure.
HTTP details: status codes, GET, caching, CORS Important
In plain words: A GraphQL server is still an HTTP server. Know which status code means what, which requests may be cached, and which origins may call you.
Common misunderstanding: "GraphQL always returns 200." Request-level failures do not: in the measured run of this chapter (no Accept header, so the legacy application/json type), a body that is not JSON returned 400 and a query that does not parse or validate returned 422, while resolver errors, complexity and depth rejections and PersistedQueryNotFound returned 200. With Accept: application/graphql-response+json the same invalid query returned 400, because gqlgen negotiates the draft's status rules (TestGraphQLResponseJSON). The GraphQL over HTTP draft says "the server SHOULD respond with a status code of 200 OK. This is the case even if a GraphQL execution error is raised", but defines request errors separately, and servers differ.
Definition: the draft defines the media type application/graphql-response+json and says "The client MUST include the media type application/graphql-response+json in the Accept header." gqlgen v0.17.86 negotiates: with that Accept it answers with that type, otherwise with application/json; transport.POST has a UseGrapQLResponseJsonByDefault field (spelled that way in the source) to flip the default. Queries may use GET (cacheable) and must use POST for mutations. CORS is not a GraphQL concern: the Middlewares chapter covers it, and the gqlgen CORS recipe sets headers with rs/cors in front of the handler.
POST /query Content-Type: application/json query or mutation
GET /query?query=...&variables=... query only (APQ-friendly)
GET /query Upgrade: websocket subscription
OPTIONS /query preflight, answered by transport.OptionsReal scenario: a CDN caches GET /query for anonymous public queries but never POST; a mobile client treats HTTP 400 and 422 as bugs in its own code (do not retry) and 5xx as transient (retry).
| Response | Meaning | Client action |
|---|---|---|
200 with errors and data | Partial response | Render data, report errors |
200 with errors, no data | Rejected by an extension (limits, APQ miss) | Fix query or register hash |
| 400 | Body not JSON | Bug in the client |
| 422 | Parse or validation error | Bug in the client; regenerate types |
| 5xx | Server or proxy failure | Retry with backoff |
Fix / how to use it: keep Cache-Control: private, no-store on authenticated responses, use globally unique IDs so clients can normalise their caches (graphql.org: "there's no URL-like primitive that provides this globally unique identifier for a given object", so the API should expose one), and put server timeouts on http.Server (net/http).
Federation pointer Good to know
In plain words: When many teams own different parts of one graph, a gateway can stitch their schemas into one. Apollo Federation is the common protocol: each service declares which types it owns and extends, and a router plans queries across them.
Common misunderstanding: "Federation is how you split a GraphQL server." Federation is for organisational scaling, not for performance. A modular monolith with one schema is simpler and faster until teams really cannot share a repository.
Definition: gqlgen has Apollo Federation support (its docs page "Apollo Federation"): a subgraph marks entity types with @key(fields: "id") (the docs also show @entityResolver(multi: true) for batched lookups) and implements an entity resolver per type; the router, not the client, calls those. This chapter does not build one: the pointer is the gqlgen federation recipe and Apollo's federation docs, both saved in the sources folder.
client -> router (supergraph schema) -> plans:
1 Book {id title} from catalog subgraph
2 Book {id rating} from ratings subgraph (entity lookup by @key id)
3 router merges the two answers into one responseReal scenario: a catalogue team owns Book, a reviews team adds Book.reviews from its own service without touching the catalogue repo; the router fetches both in parallel.
| Option | Complexity | When |
|---|---|---|
| One schema, one service | Lowest | Most products |
| Modular monolith, one schema, packages per domain | Low | Many teams, one deploy |
| Federation (router plus subgraphs) | High | Independent teams and deploys |
| Schema stitching in a gateway | Medium to high | Legacy services you cannot change |
Fix / how to use it: start with one schema, draw module boundaries inside the codebase that match the future subgraphs, and adopt federation only when deploy independence is the actual bottleneck.
Mechanics
The request lifecycle Important
In plain words: A request passes through the same stations every time: HTTP, your middleware, the transport, the extensions that can reject it, parsing and validation, and finally execution. Knowing the order tells you where each guard can stop it.
Common misunderstanding: "Limits run when the resolvers run." They run before: complexity and depth are computed from the parsed query, so an over-budget query costs one parse and nothing else.
Definition: gqlgen's handler server holds a list of transports (chosen by method, content type and Upgrade header, first match wins) and a stack of extensions implementing hooks such as OperationParameterMutator (APQ), OperationContextMutator (complexity, introspection, depth), OperationInterceptor, ResponseInterceptor and FieldInterceptor (tracing). The query document cache (SetQueryCache(lru.New[*ast.QueryDocument](1000))) skips re-parsing repeated queries.
POST /query { "query": "...", "variables": {...}, "extensions": {...} }
1 http.Server -> mux -> loaders.Middleware -> graph.RoleMiddleware -> handler.Server
2 transport.Websocket.Supports? no. Options? no. GET? no. POST? yes (application/json)
3 OperationParameterMutator: APQ resolves the query text from the hash
4 parse (query cache) + validate against the schema -> 422 on failure
5 OperationContextMutator: Introspection flag, complexity (200), Depth{8}
6 OperationInterceptor wraps: operation span starts
7 execute: fields run, directives wrap resolvers, FieldInterceptor spans, errors collected
8 response written; presenter maps errors; HTTP status chosenReal scenario: a rejected query never reaches AuthorSvc; a repeated hot query skips parsing; a panic in one resolver is recovered by SetRecoverFunc and shows up as one error entry while the other fields are served.
| Stage | Mechanism | Can stop the request? |
|---|---|---|
| Transport choice | Supports(r) in registration order | Yes, if none matches |
| Parameter mutators | APQ | Yes (PersistedQueryNotFound) |
| Parse and validate | gqlparser | Yes (422) |
| Context mutators | Introspection, complexity, depth | Yes |
| Execution | Resolvers, directives | Per field |
| Response interceptors | Tracing, logging | No |
Fix / how to use it: register the WebSocket transport first, keep the order of Use calls deliberate (APQ before limits so limits see the real query), and test the production configuration separately from development.
Exact messages and codes (measured) Must-know
In plain words: These are the strings a client or an alert rule will actually see. They were captured from the tests in this chapter's module.
Common misunderstanding: "Messages are stable API." Only extensions.code values you define are stable; gqlgen and gqlparser message wording can change between versions.
Definition: verbatim outputs from gqlgen v0.17.86 and gqlparser v2.5.31 as used in the snippets:
| Situation | Message | Code | HTTP |
|---|---|---|---|
| Complexity over limit 20 | operation has complexity 300, which exceeds the limit of 20 | COMPLEXITY_LIMIT_EXCEEDED | 200 |
| Depth over limit 4 (ours) | operation has depth 5, which exceeds the limit of 4 | DEPTH_LIMIT_EXCEEDED | 200 |
| Introspection off | introspection disabled | INTROSPECTION_DISABLED (set by our presenter) | 200 |
| Unknown hash | PersistedQueryNotFound | PERSISTED_QUERY_NOT_FOUND | 200 |
| Wrong hash with text | provided APQ hash does not match query | none | n/a |
| Unknown field | Cannot query field "boook" on type "Query". | GRAPHQL_VALIDATION_FAILED | 422 |
| Syntax error | Unexpected <EOF> | GRAPHQL_PARSE_FAILED | 422 |
| Body not JSON | json request body could not be decoded: unexpected EOF body:{ | none | 400 |
| Auth directive, anonymous | authentication required | UNAUTHENTICATED | 200 |
| Unassigned directive | directive auth is not implemented | none | 200 |
{"errors":[{"message":"internal server error","path":["book","rating"],
"extensions":{"code":"INTERNAL_SERVER_ERROR"}}],
"data":{"book":{"title":"Go To Considered","rating":null}}}Real scenario: an alert on extensions.code = COMPLEXITY_LIMIT_EXCEEDED rate spikes to catch a scraper; a dashboard counts UNAUTHENTICATED per client version after a token-format change.
| Concern | Where to look |
|---|---|
| Message wording | Source of the extension at the pinned tag |
| Status selection | transport/http_post.go, headers.go, error.go |
| Codes you own | Your presenter and directives |
Fix / how to use it: assert on extensions.code, not on message text, in tests and alerts; keep your own codes in one file and document them.
What the generated code does Good to know
In plain words: generated.go is the engine: for each type it has a function that runs the selected fields and builds the JSON, and for each list it does the per-item work in goroutines.
Common misunderstanding: "It uses reflection at request time." The generated code is plain, typed Go; reflection is used by the generator at build time to bind types.
Definition: in this module's generated.go (5,028 lines for a 75-line schema, gqlgen v0.17.86) each list marshaller creates a sync.WaitGroup, and for a list with more than one element runs go f(i) per item, with a recover that turns a panic into an error entry. That is why Book.author calls for six books arrive concurrently and the dataloader window fills. A list of exactly one element runs inline.
marshal list of 6 BookEdge:
1 wg := sync.WaitGroup; wg.Add(6)
2 for each i: go f(i) -> ec._BookEdge(ctx, sel, v[i])
3 f(i) runs the selected fields; Book.author -> resolver -> Load(...)
4 wg.Wait(); array completeReal scenario: a data race in a resolver that mutates shared state shows up only for lists of two or more items; a resolver that calls a non-thread-safe client breaks only under list queries.
| Fact | Consequence |
|---|---|
| Lists fan out into goroutines | Resolvers and services must be goroutine-safe |
| One goroutine per item | Very long lists create many goroutines; cap first |
recover per item | A panic costs one entry, not the process |
| Generated code is committed | Review diffs when you upgrade gqlgen |
Fix / how to use it: run go test -race, keep services stateless or locked, and cap page sizes.
Solving the classic problems
| Problem | Symptom | Solution | Section |
|---|---|---|---|
| N+1 queries | Latency grows with list length; query log shows repeats | Dataloader per request | Dataloaders |
| Expensive or hostile queries | CPU spikes from one client | Page cap, complexity, depth, timeouts, rate limit | Limits |
| Leaky errors | SQL text in errors[].message | Error presenter, recover func | Errors |
| Authorization holes | Data readable through a second path | Service-layer checks | Authz |
| Unbounded lists | Memory growth, slow pages | Relay connections with a cap | Pagination |
| Schema reconnaissance | Strangers read your whole schema | Introspection off, suggestions off | Introspection |
| Slow resolver hides in the tree | One field dominates p99 | Per-field tracing | Tracing |
| Request payload size | Large queries on slow links | APQ or an allow-list | APQ |
| Breaking changes | Old clients fail after a rename | Add fields, @deprecated, measure usage | below |
| Generated code drift | Compile errors after schema edits | Regenerate in CI, fail on diff | gqlgen |
Evolving the schema without versions Important
In plain words: Instead of /v2, you add new fields, mark old ones deprecated and remove them when nobody asks for them any more.
Common misunderstanding: "GraphQL has no versioning problem." Removing or changing the nullability of a field still breaks clients; the difference is that you can see which clients request which fields, and adding is always safe. See API Versioning & Evolution.
Definition: the built-in @deprecated(reason: "...") directive on fields and enum values is visible through introspection and tooling. Safe changes: add a field, add an optional argument, add an enum value (clients must handle unknown ones). Unsafe: remove or rename a field, make a nullable field non-null in output (safe) or an optional input required (unsafe), change a type.
1 add Book.isbn (nullable) safe
2 mark Book.externalId @deprecated(reason: "use isbn")
3 log operation names + fields used per client version
4 when usage is zero for N weeks: removeReal scenario: a mobile app that cannot be force-updated keeps asking for a field for two years; an operation log shows exactly which versions, so the field is removed only after they age out.
| Change | Safe for existing clients? |
|---|---|
| New field, new type, new optional argument | Yes |
| New enum value | Only if clients handle unknown values |
| Deprecate a field | Yes (a hint) |
| Remove or rename a field | No |
| Make output field nullable to non-null | Yes; the reverse is not |
| Make optional input required | No |
Fix / how to use it: require named operations from clients, record field usage in a tracing or logging extension, and publish a deprecation policy.
Choosing
| Situation | Pick | Why |
|---|---|---|
| Many client types (web, iOS, Android) with different data needs | GraphQL | Clients shape responses; one contract |
| Public API, simple resources, heavy CDN caching | REST | URLs cache; tooling is universal |
| Service-to-service, low latency, strict contracts, streaming | gRPC | Binary, generated clients, deadlines in the protocol |
| Aggregating several backends for one UI | GraphQL as a BFF over REST or gRPC services | One round trip for the client |
| Webhooks, file downloads, simple CRUD | REST | GraphQL adds nothing |
| Real-time dashboards | GraphQL subscriptions or SSE or WebSocket | Push to connected clients |
| Small team, one client | REST first | Fewer moving parts to defend |
REST vs GraphQL vs gRPC trade-offs:
| Dimension | REST | GraphQL | gRPC |
|---|---|---|---|
| Contract | OpenAPI (optional) | SDL schema (required) | .proto (required) |
| Wire format | JSON, HTTP/1.1 or 2 | JSON over HTTP, WebSocket for subscriptions | Protobuf over HTTP/2 |
| Who shapes the response | Server | Client | Server (messages are fixed) |
| Over/under-fetching | Common | Solved | Per method |
| HTTP caching | Natural | Hard (POST, one URL); persisted GET helps | Not applicable |
| Streaming | SSE, WebSocket separately | Subscriptions | Native four modes |
| Browser support | Native | Native | Needs gRPC-web or a gateway |
| Error model | HTTP status | errors array, 200 | Status codes in trailers |
| Server cost control | Per endpoint | Needs limits | Per method |
| Go tooling | net/http | gqlgen | protoc-gen-go-grpc |
A framework-neutral discussion is in REST API Design and gRPC & Protocol Buffers; REST vs GraphQL vs gRPC; the Go side of gRPC is in gRPC & Protobuf in Go.
| Library choice | Pick | When |
|---|---|---|
| gqlgen | Default | Schema-first, type-safe, rich extensions |
| graph-gophers/graphql-go | Minimal API, method-set matching | You want no codegen and accept manual binding |
| graphql-go/graphql | Code-first builder | You generate schemas programmatically at run time |
In architecture: from a single process to a distributed system
Monolith: one process, one database
One binary, one schema, one Resolver built in main from a *sql.DB-backed service. Dataloaders and ctx deadlines are the whole performance story: the loaders turn nested queries into a few WHERE id = ANY($1) calls (database/sql & pgx), and statement_timeout is the backstop. Example: this chapter's module, with store.Memory replaced by a repository: POST /query for the web app, /playground only in development, server.Config{Production: true} in the deployed binary. Start here; it is correct for most products.
Modular monolith and multiple databases
Grow the schema per domain: catalog.graphql, orders.graphql, accounts.graphql, each with its own *.resolvers.go (the follow-schema layout does this) and its own service interface in the Resolver. Modules talk through service interfaces, not through each other's tables. Each module with its own database gets its own loaders (OrdersByCustomerID), all created in the same middleware. The cost to watch is cross-module N+1: Order.customer resolves through the accounts service, so it needs a batch method on that service, not a loop.
Microservices
Two shapes. A BFF (backend for frontend): one GraphQL service owned by the client team, calling REST or gRPC services; the resolvers are thin clients and every cross-service call needs the loader treatment plus a deadline derived from ctx. Or federation (Federation pointer): each team owns a subgraph and a router plans queries. Example flow: web app sends { me { orders { items { product { name } } } } } to the BFF; the BFF calls accounts (gRPC), orders (gRPC, batched by customer id), products (gRPC, batched by product ids) and merges. What does not survive the boundary: a database transaction across services (use sagas, see Saga Pattern), a shared in-process dataloader cache, and a single trace unless you propagate traceparent.
Distributed data: replicas, caches, sharded databases, multi-region
A mutation that writes to the primary and a following query that reads a replica may not see the write: return the mutated object from the mutation (read-your-writes by construction) and route the next read to the primary for a short time (Replication, Read Replicas & Failover). Cache at the service layer by key (book:b1) or at the edge by persisted-query GET plus Cache-Control; invalidate on the mutation that changes the entity (Caching). Subscriptions need a shared bus across replicas, and a client that reconnects must refetch because the bus has no replay. Across regions, keep a subscription's WebSocket in the user's region and publish events to all regions.
Scaling path: 1×, 10×, 100×
| Load | What changes | GraphQL practice |
|---|---|---|
| 1× (one instance) | N+1 is invisible with small lists | Dataloaders from day one; page cap; tests that count queries |
| 10× (several instances behind a load balancer) | Hot queries repeat; one expensive query hurts everyone | APQ with a shared cache; complexity and depth limits; per-client rate limits; tracing per field |
| 100× (many services and clients) | Teams collide on the schema; a few operations dominate cost | Persisted-query allow-list; operation-level metrics by name; BFF per client or federation; shared event bus for subscriptions |
Lab
All commands run from docs/snippets/go/graphql-in-go/go. Outputs marked "real" were produced on Go 1.27.4 (macOS, Apple silicon) while writing this chapter; the last lab is expected, not run.
1. Run the whole suite (real)
$ export PATH=/opt/homebrew/bin:$PATH
$ gofmt -l . # no output
$ go vet ./... # no output
$ go test -race -count=1 ./...
ok academy/graphql-in-go/after 1.4s
ok academy/graphql-in-go/before 1.4s
ok academy/graphql-in-go/graph 1.4s
ok academy/graphql-in-go/limits 1.4s
ok academy/graphql-in-go/loaders 1.4s
ok academy/graphql-in-go/server 1.4s
ok academy/graphql-in-go/store 1.4s
? academy/graphql-in-go/cmd/server, graph/model, tracing [no test files]2. See the N+1 and its fix (real)
$ go test -race -count=1 -v -run 'NPlusOne|Batched|DataloaderBatches' ./before ./after ./server
--- PASS: TestNPlusOne (0.00s) # 1 list query + 6 author queries
--- PASS: TestBatched (0.00s) # 1 list query + 1 batched author query
--- PASS: TestDataloaderBatchesAuthors # same, through the real GraphQL handler3. Read the limits (real)
$ go test -count=1 -v -run 'Complexity|Depth|Introspection' ./server
server_test.go:258: operation has complexity 300, which exceeds the limit of 20
server_test.go:275: operation has depth 8, which exceeds the limit of 4
server_test.go:294: {Message:introspection disabled Path:[__schema] Extensions:map[code:INTROSPECTION_DISABLED]}4. Regenerate the code, and watch it fail on the wrong toolchain (real)
$ go tool gqlgen generate # host Go 1.27.4
internal error: package "github.com/vektah/gqlparser/v2/ast" without types was imported from "github.com/99designs/gqlgen/graphql/introspection"
$ ls graph # generated.go is gone: restore it first
$ GOTOOLCHAIN=go1.24.13 go generate ./graph # downloads Go 1.24.13 once; exit 0, no output
$ go test -count=1 ./... # all ok again5. Run the server and query it with curl (real)
$ go run ./cmd/server &
$ curl -s -X POST localhost:8080/query -H 'Content-Type: application/json' \
-d '{"query":"{ books(first: 2) { totalCount pageInfo { hasNextPage hasPreviousPage startCursor endCursor } edges { node { id title author { name } } } } }"}'
{"data":{"books":{"totalCount":6,"pageInfo":{"hasNextPage":true,"hasPreviousPage":false,"startCursor":"Ym9vazpiMQ==","endCursor":"Ym9vazpiMg=="},"edges":[{"node":{"id":"b1","title":"Notes","author":{"name":"Ada Lovelace"}}},{"node":{"id":"b2","title":"Compilers","author":{"name":"Grace Hopper"}}}]}}}
$ curl -s -X POST localhost:8080/query -H 'Content-Type: application/json' -d '{"query":"{ book(id: \"b3\") { title rating } }"}'
{"errors":[{"message":"internal server error","path":["book","rating"],"extensions":{"code":"INTERNAL_SERVER_ERROR"}}],"data":{"book":{"title":"Go To Considered","rating":null}}}
$ curl -s -X POST localhost:8080/query -H 'Content-Type: application/json' -d '{"query":"{ secretShelf { title } }"}'
{"errors":[{"message":"authentication required","path":["secretShelf"],"extensions":{"code":"UNAUTHENTICATED"}}],"data":null}
$ curl -s -X POST localhost:8080/query -H 'Content-Type: application/json' -H 'X-Demo-Role: EDITOR' \
-d '{"query":"mutation { addBook(input: {title: \"Lab\", authorId: \"a1\"}) { id title externalId publishedAt } }"}'
{"data":{"addBook":{"id":"b7","title":"Lab","externalId":"d3da7334-6231-4f26-b37f-387eed92486d","publishedAt":"2026-11-28T13:07:33Z"}}}6. Production mode (real)
$ kill %1 # stop the development server first: both bind :8080
$ APP_ENV=production go run ./cmd/server &
$ curl -s -X POST localhost:8080/query -H 'Content-Type: application/json' -d '{"query":"{ __schema { queryType { name } } }"}'
{"errors":[{"message":"introspection disabled","path":["__schema"],"extensions":{"code":"INTROSPECTION_DISABLED"}}],"data":{"__schema":null}}
$ curl -s -o /dev/null -w "playground %{http_code}\n" localhost:8080/playground
playground 404
$ curl -s -X POST localhost:8080/query -H 'Content-Type: application/json' -d '{"query":"{ boook { title } }"}'
{"errors":[{"message":"Cannot query field \"boook\" on type \"Query\".","locations":[{"line":1,"column":3}],"extensions":{"code":"GRAPHQL_VALIDATION_FAILED"}}],"data":null}7. A subscription from a browser (expected, not run)
Open /playground in development, run subscription { bookAdded { id title } }, then in a second tab run the addBook mutation with the X-Demo-Role: EDITOR header. Expected: the first tab shows { "bookAdded": { "id": "b8", "title": "..." } } immediately. The automated version is TestSubscriptionOverWebSocket.
For PHP/Laravel developers
The closest Laravel counterpart is Lighthouse (composer require nuwave/lighthouse), a schema-first server: you write graphql/schema.graphql and most fields are driven by directives that map to Eloquent instead of resolver functions. Where gqlgen makes you write the resolver and wire the service, Lighthouse makes you annotate the field: users: [User!]! @all, posts: [Post!]! @paginate, author: User! @belongsTo. Custom logic goes into an invokable class under App\GraphQL\Queries or App\GraphQL\Mutations with __invoke(mixed $root, array $args).
# Lighthouse: the schema does most of the work through directives
type Query {
posts: [Post!]! @paginate
}
type Post {
title: String!
author: User! @belongsTo
}
type Mutation {
addUserToCompany(user: ID! @bind(class: "App\\Models\\User"), company: ID!): Boolean!
}<?php
// Lighthouse custom mutation: an invokable class (shape from the Lighthouse docs).
namespace App\GraphQL\Mutations;
final class AddUserToCompany
{
/** @param array{user: \App\Models\User, company: int} $args */
public function __invoke(mixed $root, array $args): bool
{
$user = $args['user'];
$user->company_id = $args['company'];
return $user->save();
}
}| Concern | Lighthouse (Laravel) | gqlgen (Go) |
|---|---|---|
| Schema style | Schema first (graphql/schema.graphql) | Schema first (graph/*.graphql) |
| Binding to data | Directives on Eloquent (@all, @find, @belongsTo, @hasMany) | Resolver methods, struct field binding, autobind |
| N+1 | Eager loading hints via @belongsTo, @hasMany, @with; custom batch loaders documented | Dataloader per request (dataloadgen) |
| Pagination | @paginate directive | Relay connection written by you |
| Auth | @guard, @can directives | @auth directive you write, plus services |
| Subscriptions | Pusher or Laravel Echo broadcaster drivers | WebSocket transport, channel returned by the resolver |
| Where it runs | One PHP request per process; no shared memory | One process, many goroutines, shared in-process state |
| Cost model | Each request is isolated; stateless by default | Lists fan out into goroutines; resolvers must be thread-safe |
| Code generation | None | generated.go |
Lighthouse's N+1 documentation puts the problem the same way as this chapter: "The associated author for each post would be lazily loaded, querying the database once per post." The Eloquent answer is eager loading; the Go answer is a loader, because there is no ORM relation graph to eager-load from. For subscriptions, Lighthouse says "Unless you delete a subscription, it will continue to broadcast events after the client has disconnected", a reminder that lifecycle management differs: gqlgen ties it to the request ctx. I did not verify Lighthouse's depth, complexity and introspection settings in this session; check its security documentation before relying on them.
Common misconceptions
| Belief | Reality |
|---|---|
| GraphQL replaces the database layer | It is an API layer; resolvers still call services and databases |
| GraphQL is faster than REST | Fewer round trips, not less server work; without a loader it is slower |
| Always 200 means errors are hidden | Errors are in the body by design; request-level failures can be 400 or 422 |
| A global dataloader is fine | One loader per request, or you leak data and serve stale values |
| Introspection off is security | It hides the map; limits and authorization still matter |
| APQ is a security feature | It is a bandwidth and cache feature; an allow-list is the security feature |
| gqlgen does DI | It calls the Resolver you build; wiring is yours |
I can edit generated.go | It is overwritten on every generate |
Helpers belong in schema.resolvers.go | gqlgen moves unknown code there into a comment; use another file |
A Resolver field may be named Books | A same-named resolver method shadows it; use BookSvc |
| Protecting one field protects the data | Another path to the same object bypasses it; authorize in the service layer |
| Cursors are offsets | Cursors are opaque positions; keyset cursors stay stable under inserts |
| Subscriptions are durable messaging | Push to connected clients only; refetch on reconnect |
go tool gqlgen generate works on any Go | The pinned v0.17.86 failed on Go 1.27.4 and deleted generated.go |
| gqlgen batches an array of operations | Not in v0.17.86's POST transport |
Cheat sheet
| Topic | Remember |
|---|---|
| Pin | gqlgen v0.17.86 for go 1.24; go get -tool github.com/99designs/gqlgen@v0.17.86 |
| Generate | GOTOOLCHAIN=go1.24.13 go generate ./graph; commit the output; CI fails on diff |
| Files you edit | schema.graphql, gqlgen.yml, your models, resolver bodies, resolver.go |
| Files you never edit | generated.go, models_gen.go |
| DI | Resolver struct with small interfaces, built in main |
| Resolver fields | Do not name them like schema fields (Books); use BookSvc |
| N+1 | One dataloader per request, fetch returns values in key order |
| ctx | First argument everywhere; never context.Background() in a resolver |
| Errors | One presenter, stable extensions.code, hide internals, nullable fields for partial responses |
| Pagination | Relay connection, opaque keyset cursor, cap first |
| Limits | Page cap + FixedComplexityLimit with list multipliers + depth limit + timeouts |
| Production | Introspection off, playground unmounted, suggestions off |
| APQ | Cache only; allow-list for security; share the cache across replicas |
| Subscriptions | WebSocket transport first, CheckOrigin, never block Publish, unsubscribe on ctx.Done() |
| Tests | client.New(handler), RawPost for partial responses, assert query counts, -race |
| Status | 200 for execution errors; 400/422 for malformed or invalid requests (no Accept) |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why does a nested GraphQL query often cause N+1 queries, and how do you fix it? Must-know
Answer
Answer: The list resolver runs one query, and a field resolver on each item (Book.author) runs another, so 6 books cost 7 queries. The fix is a dataloader created per request: each Load(key) joins a batch, the loader waits a few milliseconds, and one WHERE id = ANY($1) serves all of them (see Dataloaders). Assert the query count in a test.
2 — What is the difference between a field that is a struct field and one with a resolver? Must-know
Answer
Answer: A matching struct field is read directly with no function call. A resolver exists when the Go type has no matching field or when @goField(forceResolver: true) forces one, and it runs only when the client selects the field. Resolver fields inside lists are where N+1 appears (Field-level resolvers).
3 — A resolver for a nullable field returns an error. What does the client receive? Must-know
Answer
Answer: HTTP 200 with data containing the rest of the query and null for that field, plus an errors entry with the field's path. If the field were non-null, the null would propagate to the nearest nullable parent. This is the spec's partial response (Errors).
4 — Where should authorization live, and why not only in a directive? Must-know
Answer
Answer: Authenticate in HTTP middleware, make coarse role checks with a directive, and enforce per-object rules in the service layer. A directive protects one field, but the same object is reachable through other fields (author { books }, search, mutation payloads), so the service must check (Authentication and authorization).
5 — How do you stop one client from sending a query that costs a thousand times more than normal? Must-know
Answer
Answer: Layer defences: cap first per list, set extension.FixedComplexityLimit with custom list multipliers so cost is first * childComplexity, add a depth limit (gqlgen has none built in; the chapter writes one), put deadlines on ctx and rate-limit by client. Limits run after parsing and before execution, so a rejected query is cheap (Limits).
6 — Why are Relay cursors opaque, and what do they encode here? Important
Answer
Answer: Opaque cursors let the server change how it pages without breaking clients, and the spec tells clients not to parse them. Here the cursor is base64 of book:<id>; the server decodes it to an id and runs WHERE id > $1 ORDER BY id LIMIT first+1, which stays stable under inserts and costs the same at any depth (Pagination).
7 — Why must the WebSocket transport be registered first, and what must you configure on it? Important
Answer
Answer: Transports are tried in registration order; the gqlgen recipe registers WebSocket before POST so an upgrade request is handled as a WebSocket. Configure Upgrader.CheckOrigin against an allow-list, InitFunc for authentication (browsers cannot set headers) and KeepAlivePingInterval. In v0.17.86 the upgrader is gorilla's; later releases switched to coder/websocket (Subscriptions).
8 — Is automatic persisted queries a security feature? Important
Answer
Answer: No. APQ lets any client register any query by sending text and hash, so it saves bandwidth and enables GET caching but blocks nothing. An allow-list of hashes registered at deploy time, refusing the rest, is the security feature (APQ).
9 — How do you disable introspection and the playground in production, and does that secure the API? Important
Answer
Answer: gqlgen has introspection off unless you Use(extension.Introspection{}), so install it (and mount playground.Handler) only when not in production, and consider SetDisableSuggestion(true). It removes reconnaissance convenience only; authorization, limits and rate limiting still do the security work (Introspection).
10 — Why does gqlgen's generated resolver method Books break a Resolver.Books field, and what is the fix? Important
Answer
Answer: The generated queryResolver embeds *Resolver and has its own method Books; the outer method shadows the promoted field, so r.Books.BookByID fails to compile. Name injected services differently (BookSvc). Helpers placed in schema.resolvers.go have a related trap: gqlgen moves them into a comment on regeneration (gqlgen).
11 — Why does the dataloader's cache have to be per request? Good to know
Answer
Answer: A loader caches by key for its lifetime. A global one would return one user's data to another and never see updates. dataloadgen's README says a Loader is created per request; graph-gophers' README says its cache is for short-lived loaders only (Dataloaders).
12 — What do client.New and RawPost give you in tests that Post does not? Good to know
Answer
Answer: client.New(handler) calls your real handler tree in memory, no port needed. Post unpacks data into a struct and returns a RawJsonError when errors is present; RawPost returns Data and the raw Errors so you can assert a partial response and extensions.code. Use httptest.NewRecorder when you need status codes or headers (Testing).
Glossary
| Term | Meaning |
|---|---|
| GraphQL | Query language and execution model for APIs, specified at spec.graphql.org |
| SDL | Schema Definition Language: the text format for types and directives |
| Schema | The set of types, fields and directives a server exposes |
| Query | Read operation; fields may execute in parallel |
| Mutation | Write operation; top-level fields execute serially |
| Subscription | Long-lived operation that streams events (WebSocket or SSE) |
| Type / object type | Named set of fields |
| Input type | Object type used for arguments |
| Enum | Type with a fixed set of values |
| Interface | Abstract type with shared fields |
| Union | Type that is one of several object types |
| Scalar | Leaf type: Int, Float, String, Boolean, ID, or custom |
Non-null (!) | Field or item that may never be null |
List ([T]) | Ordered collection type |
| Selection set | The { ... } fields requested under a type |
| Fragment | Reusable selection set; inline fragment ... on T |
| Alias | Rename of a field in the response; allows the same field twice |
| Variable | Typed parameter passed beside the query text |
| Directive | @name(args) annotation with behaviour |
@deprecated | Built-in directive marking a field or enum value as discouraged |
@goField | gqlgen directive controlling binding (forceResolver, name) |
| Resolver | Function producing a field's value |
| Field-level resolver | Resolver for one field, run only if selected |
Resolver struct | gqlgen's root dependency holder |
| ResolverRoot | Generated interface exposing per-type resolvers |
| DirectiveRoot | Generated struct holding directive implementations |
gqlgen.yml | gqlgen config: schema, exec, model, resolver, autobind, models |
autobind | Config list of Go packages searched for same-named types |
models | Config mapping of schema types to Go types |
| Executable schema | Generated NewExecutableSchema(Config) the handler runs |
| Resolver stub | Generated method with a panic(not implemented) body |
| Schema-first | Write SDL, derive Go |
| Code-first | Write Go, derive the schema |
| Dataloader | Per-request batch-and-cache for key lookups |
| N+1 | One list query plus one query per item |
| dataloadgen | github.com/vikstrous/dataloadgen, generics-based loader |
| graph-gophers/dataloader | Port of Facebook's DataLoader for Go |
| gqlerror | gqlparser/v2/gqlerror error type with path, locations, extensions |
| Extensions (error) | Free-form map on an error; code by convention |
| Partial response | Response with both data and errors |
| Error presenter | gqlgen hook that maps errors before they reach the client |
| Relay connection | Pagination shape: edges { cursor node } and pageInfo |
| Cursor | Opaque string marking a position |
| Keyset pagination | Paging by WHERE key > last instead of OFFSET |
| Complexity limit | Rejects queries whose computed cost exceeds a budget |
| Depth limit | Rejects queries nested beyond N levels |
| Introspection | __schema and __type queries that describe the schema |
| Playground | Browser IDE for running queries, needs introspection |
| APQ | Automatic persisted queries: hash first, text on a miss |
| Persisted-query allow-list | Only pre-registered hashes are accepted |
| Batching | Dataloader, operation-array and alias batching |
| Transport | POST, GET, Websocket, SSE, Options in gqlgen |
graphql-transport-ws | Current WebSocket subprotocol for GraphQL |
| Federation | Apollo protocol for composing subgraphs behind a router |
| BFF | Backend for frontend: a client-specific API layer |
| OpenTelemetry | Vendor-neutral tracing and metrics standard |
client.New | gqlgen's in-memory test client over an http.Handler |
| Lighthouse | Laravel GraphQL package (nuwave/lighthouse) |
References
- GraphQL Specification, October 2021: https://spec.graphql.org/October2021/
- GraphQL Specification, working draft: https://spec.graphql.org/draft/
- GraphQL over HTTP (draft): https://graphql.github.io/graphql-over-http/draft/
- GraphQL Cursor Connections Specification (Relay): https://relay.dev/graphql/connections.htm
- graphql.org Learn, Queries: https://graphql.org/learn/queries/
- graphql.org Learn, Schemas and Types: https://graphql.org/learn/schema/
- graphql.org Learn, Pagination: https://graphql.org/learn/pagination/
- graphql.org Learn, Caching: https://graphql.org/learn/caching/
- graphql.org Learn, Authorization: https://graphql.org/learn/authorization/
- graphql.org Learn, Security: https://graphql.org/learn/security/
- graphql.org Learn, Best Practices: https://graphql.org/learn/best-practices/
- gqlgen documentation, home: https://gqlgen.com/
- gqlgen, Getting started: https://gqlgen.com/getting-started/
- gqlgen, Configuration: https://gqlgen.com/config/
- gqlgen, Resolvers: https://gqlgen.com/reference/resolvers/
- gqlgen, Dataloaders: https://gqlgen.com/reference/dataloaders/
- gqlgen, Schema directives: https://gqlgen.com/reference/directives/
- gqlgen, Handling errors: https://gqlgen.com/reference/errors/
- gqlgen, Subscriptions: https://gqlgen.com/recipes/subscriptions/
- gqlgen, Query complexity: https://gqlgen.com/reference/complexity/
- gqlgen, Automatic persisted queries: https://gqlgen.com/reference/apq/
- gqlgen, Introspection: https://gqlgen.com/reference/introspection/
- gqlgen, Scalars: https://gqlgen.com/reference/scalars/
- gqlgen, Apollo Federation: https://gqlgen.com/recipes/federation/
- gqlgen, CORS recipe: https://gqlgen.com/recipes/cors/
- gqlgen, Feature comparison: https://gqlgen.com/feature-comparison/
- gqlgen README: https://raw.githubusercontent.com/99designs/gqlgen/master/README.md
- gqlgen v0.17.86 source, WebSocket transport: https://raw.githubusercontent.com/99designs/gqlgen/v0.17.86/graphql/handler/transport/websocket.go
- gqlgen v0.17.86 source, complexity extension: https://raw.githubusercontent.com/99designs/gqlgen/v0.17.86/graphql/handler/extension/complexity.go
- gqlgen v0.17.86 source, APQ extension: https://raw.githubusercontent.com/99designs/gqlgen/v0.17.86/graphql/handler/extension/apq.go
- gqlgen v0.17.86 source, POST transport: https://raw.githubusercontent.com/99designs/gqlgen/v0.17.86/graphql/handler/transport/http_post.go
- gqlgen v0.17.86 source, test client README: https://raw.githubusercontent.com/99designs/gqlgen/v0.17.86/client/readme.md
- gqlgen v0.17.86
go.mod: https://raw.githubusercontent.com/99designs/gqlgen/v0.17.86/go.mod - vikstrous/dataloadgen README: https://raw.githubusercontent.com/vikstrous/dataloadgen/master/README.md
- vikstrous/dataloadgen v0.0.10 source: https://raw.githubusercontent.com/vikstrous/dataloadgen/v0.0.10/dataloadgen.go
- graph-gophers/dataloader README: https://raw.githubusercontent.com/graph-gophers/dataloader/master/README.md
- graph-gophers/graphql-go README: https://raw.githubusercontent.com/graph-gophers/graphql-go/master/README.md
- graphql-go/graphql README: https://raw.githubusercontent.com/graphql-go/graphql/master/README.md
- graphql-ws protocol: https://raw.githubusercontent.com/enisdenjo/graphql-ws/master/PROTOCOL.md
- gorilla/websocket README: https://raw.githubusercontent.com/gorilla/websocket/main/README.md
- Apollo, Automatic persisted queries: https://www.apollographql.com/docs/apollo-server/performance/apq
- Apollo, Federation overview: https://www.apollographql.com/docs/graphos/schema-design/federated-schemas/federation
- OWASP GraphQL Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/GraphQL_Cheat_Sheet.html
- OpenTelemetry for Go: https://opentelemetry.io/docs/languages/go/
- Lighthouse, Installation: https://lighthouse-php.com/master/getting-started/installation.html
- Lighthouse, The N+1 query problem: https://lighthouse-php.com/master/performance/n-plus-one.html
- Lighthouse, Eloquent and pagination: https://lighthouse-php.com/master/eloquent/getting-started.html
- Lighthouse, Subscriptions: https://lighthouse-php.com/master/subscriptions/getting-started.html
- Lighthouse, Directives reference: https://lighthouse-php.com/master/api-reference/directives.html
- gRPC introduction: https://grpc.io/docs/what-is-grpc/introduction/
- Go 1.21 release notes (
min,max): https://go.dev/doc/go1.21 - Go 1.22 release notes (per-iteration loop variables): https://go.dev/doc/go1.22
- Go 1.24 release notes (
tooldirective): https://go.dev/doc/go1.24