← Dedicated courses

GIN TUTORIAL · GO WEB SERVICES · 53 LESSONS

Gin: web services in Go

Start with an engine and two routes, finish with a tested REST API that talks to storage and upstream services and survives retries, concurrent edits and rolling deploys. Every example runs against upstream Gin v1.12 with httptest, so you can follow along without opening a port.

Start with “Your first Gin service: an engine, two routes and a test request” →

Who it is for

Go programmers who want to build HTTP APIs with Gin — whether you are writing your first handler or hardening a service that already runs in production.

Before you start

Basic Go: functions, structs, interfaces, errors and the net/http request model.

What you will be able to do

  • Route, bind and validate requests from paths, queries, headers, forms, JSON and file uploads.
  • Write middleware for authentication, CORS, rate limiting, request IDs, timeouts and metrics.
  • Design a REST resource with pagination, problem-details errors, idempotency keys and ETags.
  • Test the whole router in-process and run it behind an explicit http.Server with graceful shutdown.
  • Pass request contexts to storage, apply JSON Merge Patch, stream imports and exports, and verify signed webhooks.
  • Call upstream APIs with budgets, retries and circuit breakers, version the API and ship release builds through rolling deploys.

Unit 1. Gin foundations

Engines, routes, parameters, groups, binding sources, validators, JSON, uploads, templates and 404/405 handling.

  1. Your first Gin service: an engine, two routes and a test request

    Build a Gin engine, register routes with a path parameter and exercise them without opening a port.

    4 min · Worked lesson

  2. Path parameters in Gin: :param takes one segment, *wildcard takes the rest, conflicts panic at boot

    Declare Gin route templates with :param and *wildcard, predict how slashes and escapes resolve, and label metrics with c.FullPath().

    6 min · Worked lesson

  3. Query strings and forms in Gin: tell absent from empty, parse numbers strictly, bound every limit

    Read query and form values with the Gin helper that matches the case, convert them with strconv and reject bad input with a clear 400.

    5 min · Worked lesson

  4. Gin route groups: prefixes and middleware are copied at registration, so test the route table

    Organize a Gin API into nested, versioned groups with scoped middleware and prove with r.Routes() that every route has the protection you intended.

    5 min · Worked lesson

  5. Gin JSON responses: know what each renderer writes and return a DTO, never your storage model

    Choose between c.JSON, PureJSON, IndentedJSON, SecureJSON and AsciiJSON by their exact output, set status codes deliberately and render a response DTO with correct omitempty and omitzero tags.

    5 min · Worked lesson

  6. Gin binding sources: bind path, query, headers and body separately, and cache the body to read it twice

    Bind each request source with its own Gin binder and tag, predict what content-type-driven ShouldBind reads, and decode one body twice with ShouldBindBodyWithJSON.

    5 min · Worked lesson

  7. Custom validators in Gin: register domain rules once and return field errors clients can rely on

    Register a custom tag and a struct-level rule on Gin's validator, validate slice elements with dive and convert validator errors into a stable field-level JSON response.

    5 min · Worked lesson

  8. Writing Gin middleware: what c.Next returns to, what Abort does not do, and typed request values

    Write Gin middleware that runs code after c.Next, stops the chain with Abort and return, shares typed values through c.Set and c.Get, and is ordered so logs see the final outcome.

    5 min · Worked lesson

  9. File uploads in Gin: cap the request, sniff the bytes and never let the client name the file

    Accept a multipart upload in Gin with a hard size cap, decide its type from its content, generate the storage name yourself and test it with a request built by mime/multipart.

    5 min · Worked lesson

  10. Server-rendered HTML in Gin: embed the templates, trust contextual escaping, cache assets on purpose

    Render html/template pages with c.HTML from templates parsed out of an embedded file system, serve embedded static assets with StaticFS and set cache headers per kind of asset.

    5 min · Worked lesson

  11. 404, 405 and redirects in Gin: answer misses in your own format and pick redirect codes by what must survive

    Configure NoRoute, NoMethod and HandleMethodNotAllowed for consistent JSON 404 and 405 responses with a correct Allow header, and choose between 301, 302, 303, 307 and 308 for redirects.

    5 min · Worked lesson

Unit page →

Unit 2. Gin in production

Middleware, bounded input, authentication, CORS, rate limits, logging, timeouts, streaming, health, caching and shutdown.

  1. Gin routing and middleware: follow the chain and stop it deliberately

    Explain route groups, middleware order and the difference between Abort and return.

    3 min · Worked lesson

  2. Gin input: size limits, binding and business validation are separate

    Reject oversized or invalid input before performing a business side effect.

    3 min · Worked lesson

  3. Gin contexts and goroutines: extract a job, do not retain the response

    Give background work a bounded owner without keeping a pooled Gin context alive.

    3 min · Worked lesson

  4. Trusted proxies: forwarded headers are not proof of identity

    Configure proxy trust explicitly and keep client IP separate from authentication.

    3 min · Worked lesson

  5. Gin errors and tests: one response owner, explicit failure cases

    Test handler contracts through ServeHTTP without confusing recovery with rollback.

    3 min · Worked lesson

  6. Gin in production: the http.Server owns budgets and shutdown

    Configure native server timeouts and distinguish HTTP drain from worker completion.

    3 min · Worked lesson

  7. Bearer authentication in Gin: verify once at the group boundary, hand handlers a typed principal

    Write middleware that verifies an HMAC-signed bearer token, stores a typed principal and answers 401 or 403 for the right reasons.

    6 min · Worked lesson

  8. CORS by hand in Gin: an exact origin allow-list, real preflights and Vary: Origin

    Implement CORS middleware that answers preflights, echoes only allow-listed origins, sets Vary correctly and is never mistaken for access control.

    5 min · Worked lesson

  9. Rate limiting in Gin: a token bucket per identity, a bounded map and an honest Retry-After

    Limit each client with golang.org/x/time/rate, pick a key clients cannot forge, bound the limiter map and refuse with 429 and Retry-After.

    5 min · Worked lesson

  10. Request IDs and access logs in Gin: log the route template and the ID, never the credential

    Add request-ID middleware and a structured slog access log that records low-cardinality routes, redacts credentials and can be tested byte for byte.

    5 min · Worked lesson

  11. Request deadlines in Gin: one context budget, cooperative handlers, no writes from a second goroutine

    Give each request a deadline that downstream calls inherit, map its expiry to 504, and avoid the timeout patterns that race on the response.

    5 min · Worked lesson

  12. Server-Sent Events in Gin: flush every event, send heartbeats, stop on the request context

    Stream SSE from a Gin handler that flushes events, sends heartbeats, ends when the client leaves and survives http.Server's WriteTimeout.

    5 min · Worked lesson

  13. Health and metrics in Gin: simple liveness, budgeted readiness, counters keyed by route template

    Separate liveness from readiness, check dependencies within a short budget, and count requests by route template and status class.

    5 min · Worked lesson

  14. Conditional GETs in Gin: strong ETags from response bytes, 304 Not Modified and safe Cache-Control

    Serve ETag and Last-Modified validators, answer conditional requests with 304, and choose Cache-Control so private data never lands in a shared cache.

    6 min · Worked lesson

Unit page →

Unit 3. Gin project: a complete REST API

Layout, dependencies, CRUD, pagination, problem details, idempotency keys, optimistic concurrency, API tests and startup.

  1. Lay out a Gin service so every import points toward the domain

    Organize a Gin API into cmd/api, httpapi, notes and store packages whose imports point toward the domain, with all concrete wiring in main.

    5 min · Worked lesson

  2. Give Gin handlers their dependencies through a struct, not globals or context keys

    Write handlers as methods on a struct built by a constructor, depend on small consumer-defined interfaces and swap in a fake store for tests.

    5 min · Worked lesson

  3. Full CRUD on one resource: exact status codes, a Location header and PUT versus PATCH

    Implement create, read, replace, patch and delete for notes with correct status codes, a Location header and presence-aware PATCH fields.

    5 min · Worked lesson

  4. Paginate with opaque cursors, a bounded limit and a total order; filter only through allow-lists

    Serve stable pages of notes with keyset cursors, cap the page size and accept only allow-listed filter and sort parameters.

    5 min · Worked lesson

  5. One error envelope: RFC 9457 problem details mapped from domain errors in one middleware

    Return application/problem+json for every failure by mapping a small domain error taxonomy to HTTP statuses in a single Gin middleware.

    5 min · Worked lesson

  6. Make POST safe to retry with Idempotency-Key: fingerprint, reserve, replay and expire

    Add Idempotency-Key handling to POST /notes so retries replay the original response, conflicting reuse is rejected and in-flight duplicates wait.

    5 min · Worked lesson

  7. Stop lost updates with versions, ETag and If-Match: 428 when missing, 412 when stale

    Version the notes resource, expose the version as an ETag and require If-Match on writes so a stale client cannot overwrite a newer edit.

    5 min · Worked lesson

  8. Table-driven API tests through the real router: status, headers and JSON compared by meaning

    Write table-driven tests that send requests through the real Gin router with fakes and assert status, contract headers and semantically compared JSON bodies.

    5 min · Worked lesson

  9. Start from validated configuration and wire the whole service in one composition root

    Load and validate configuration from the environment, fail fast with every problem listed, and wire store, service, handlers, engine and http.Server with signal-driven shutdown.

    5 min · Worked lesson

Unit page →

Unit 4. Gin and your data

Request contexts, JSON Merge Patch, safe filters, batched includes, response caches, streaming import and export, async jobs and signed webhooks.

  1. *gin.Context is a pooled struct, not your request context: pass c.Request.Context() to stores and goroutines

    Predict what *gin.Context returns as a context.Context under each ContextWithFallback setting and give stores and background work a context that is actually canceled, or deliberately not.

    7 min · Worked lesson

  2. PATCH with JSON Merge Patch in Gin: keep absent, null and value apart, then validate the merged resource

    Implement an RFC 7396 merge-patch endpoint in Gin that distinguishes absent from null, enforces application/merge-patch+json with 415, and validates the merged result before storing it.

    6 min · Worked lesson

  3. Gin list filters to parameterized SQL: parse strictly, bound IN lists, escape LIKE, end with a tiebreaker

    Write a pure function that turns a Gin list request into SQL text and arguments, with allow-listed sorts, a placeholder for every value, escaped LIKE patterns, bounded IN lists and a unique tiebreaker.

    6 min · Worked lesson

  4. ?include= without N+1 in Gin: one batched loader per relation, a bounded errgroup and list-order output

    Serve optional related data on a Gin list endpoint with one batched lookup per relation, bounded concurrent loads and deterministic output, and prove the query count by counting store calls.

    6 min · Worked lesson

  5. Cache public GETs in Gin: key by route template, bypass identity, coalesce misses, invalidate on write

    Build a Gin middleware that caches public GET responses under a route-template key, never stores per-user responses, coalesces concurrent misses with singleflight and stays correct across writes, TTLs and conditional requests.

    7 min · Worked lesson

  6. NDJSON imports in Gin: cap the body, decode one bounded line at a time, report each row by its line number

    Build an NDJSON import endpoint that bounds the body and each line, validates rows one at a time and returns a per-line report whose status matches what was written.

    7 min · Worked lesson

  7. Streaming CSV exports in Gin: keyset pages, two flushes, formula-safe cells and an abort on late failure

    Stream a large CSV from a Gin handler page by page with a safe download filename and formula-safe cells, and make a failure after the first byte visible to the client.

    8 min · Worked lesson

  8. Long work behind 202 Accepted in Gin: a bounded queue, fixed workers, a job resource and an honest 503

    Accept slow work with 202 and a job Location, bound it with a queue and a fixed worker pool, refuse overload with 503 and Retry-After, and keep jobs running after the request ends.

    7 min · Worked lesson

  9. Signed webhooks in Gin: verify the raw bytes, reject stale timestamps, dedupe event IDs, answer fast

    Receive signed webhooks in Gin by authenticating the raw body before binding, rejecting replays, deduplicating deliveries and choosing status codes that make the sender retry only when a retry can help.

    8 min · Worked lesson

Unit page →

Unit 5. Gin in the wider system

Upstream clients, retries and circuit breakers, compression, ranged downloads, content negotiation, versioning, contract tests, admin endpoints, release builds and rolling deploys.

  1. Upstream calls from Gin: one shared client, the request deadline, a bounded body and your own error codes

    Call an upstream HTTP API from a Gin handler through a shared, budgeted http.Client and map every failure to your own 404, 502 or 504 without leaking upstream details.

    7 min · Worked lesson

  2. Retrying upstream calls from Gin: only when safe, jittered backoff, a retry budget and a circuit breaker

    Wrap upstream calls in a retry policy that respects idempotency, Retry-After and a shared budget, and use a circuit breaker so Gin answers 503 quickly while a dependency is down.

    7 min · Worked lesson

  3. Gzip in Gin by hand: negotiate q-values, wrap the writer, add Vary and know what never to compress

    Write a gzip middleware for Gin that negotiates Accept-Encoding correctly and skips responses that must not be compressed, and accept gzip request bodies without a decompression-bomb hole.

    6 min · Worked lesson

  4. File downloads in Gin: ServeContent for ranges and validators, a safe Content-Disposition, files opened by ID

    Serve downloadable files from Gin with correct Range, If-Range, ETag and HEAD behavior, a Content-Disposition built by mime.FormatMediaType and file access confined to an os.Root.

    6 min · Worked lesson

  5. Content negotiation in Gin: what NegotiateFormat really matches, 406 in your format and Vary: Accept

    Serve JSON, CSV and HTML from one Gin handler with q-value-aware negotiation, a 406 that lists what is available, Vary: Accept for caches and a ?format= override where URLs must name the representation.

    6 min · Worked lesson

  6. API versions in Gin: one service under /v1 and /v2, an adapter per version, and a v1 that announces its sunset

    Serve two API versions from one service through per-version DTO adapters, mark v1 with Deprecation, Sunset and successor-version links, and test that v1 routes survive until the announced date.

    6 min · Worked lesson

  7. Keep the OpenAPI document and the Gin router honest: diff routes, operations and status codes in a test

    Write a test that converts engine.Routes() to OpenAPI path templates, reports routes and operations that exist on only one side, and checks recorded status codes against declared responses.

    5 min · Worked lesson

  8. Debug endpoints in Gin: pprof and expvar on a separate admin engine and listener, never on the public router

    Mount net/http/pprof and expvar on an admin-only Gin engine behind a network and token guard, and prove with httptest that the public engine does not serve them.

    5 min · Worked lesson

  9. Shipping a Gin binary: release mode, a /version endpoint from build info, static builds and a non-root image

    Build a Gin service for production with release mode, -trimpath, -ldflags -X and CGO_ENABLED=0, report its identity from runtime/debug build info, and package it in a minimal non-root image.

    6 min · Worked lesson

  10. Surviving a rolling deploy in Gin: fail readiness, keep serving through a drain delay, then Shutdown

    Implement and test a SIGTERM sequence that flips readiness to 503, keeps serving while load balancers stop routing, disables keep-alives, and shuts the http.Server down within a grace period the platform honors.

    6 min · Worked lesson

Unit page →

Related: Go services · Around Go: SQL services · Web application security