Development guide for the Iris v14 Go web framework: builder chain, routing macros, rest helpers, error mapping, auth SDK, middleware, and testing.

GitHub stars
25.6K

Install

/plugin install iris@kataras-iris

Run it inside Claude Code after adding the marketplace with /plugin marketplace add kataras/iris.

Contents

Discovered from source

Skills 1

Iris Web Framework v14

Quick Start

package main

import "github.com/kataras/iris/v14"

func main() {
    app := iris.New()
    app.Get("/", func(ctx iris.Context) {
        ctx.JSON(iris.Map{"message": "Hello, World!"})
    })
    app.Listen(":8080")
}
  • Module path: github.com/kataras/iris/v14
  • Go 1.27+

For a complete guided walkthrough of the recommended stack (builder, controllers, rest helpers, error mapping, DI, testing), see getting-started-tutorial.md.

Reference Index

Load the one that matches the task; each is self-contained.

ReferenceLoad it when
getting-started-tutorial.mdBuilding a v14 app from scratch, end to end
migration-v12-to-v14.mdConverting v12 code, or a v12 API does not compile
architecture-and-patterns.mdBuilder chain, DI, service lifecycle, layering, patches
routing-and-macros.mdRoute registration, path macros, subdomains, router wrappers
context-api.mdReading a request or writing a response
rest-helpers.mdctx.BindJSON, OK/Created/NoContent, pagination
sse.mdServer-Sent Events: streaming a response, or reading somebody else's
ai.mdAI backends: model streams, relays, upstream failure classification
error-handling.mdCanonical codes, error mapping, validation, privacy
middleware-reference.mdAny of the 31 bundled middleware packages
builtin-controllers.mdGeneric MVC controllers, file server, API graph, sitemap
authentication-sdk.mdJWT, identity server, OAuth2, RBAC
security-hardening.mdSecure defaults, CSRF, headers, production checklist
database-and-persistence.mdRepository wiring, kataras/pg, driver error mapping
caching.mdCache headers, 304s, server-side response cache
i18n.mdTranslations, pluralization, language detection
observability.mdAccess logs, request IDs, monitor, pprof, profiling
performance.mdStreaming, benchmarks, what the framework already does
http-client.mdOutbound HTTP calls from a service
testing-guide.mdhttptest, handler and controller tests
configuration-and-deployment.mdOptions, TLS, tunnels, graceful shutdown

Install and Run

mkdir myapp && cd myapp
go mod init myapp
go get github.com/kataras/iris/v14@latest
go run .

There is no built-in CLI and no live reload. Restart the process on change, under whatever file watcher you already use. See configuration-and-deployment.md.

Architecture Overview

Three application creation modes:

ModeWhen to Use
iris.NewBuilder()Recommended. Fluent step-by-step builder with built-in best practices
iris.New()Manual setup with full control
iris.Default()Quick prototyping (debug logging, CORS *, compression, recovery)

Builder Pattern (Recommended)

iris.NewBuilder().
    Prefix("/api").
    AllowOrigin("*").
    Compression(true).
    LogRequests(true).
    Health(true, "production", "team@company.com").
    Errors(errors.NewOptions().MapErrors(errors.NotFound, sql.ErrNoRows)).
    Deferrables(db).
    Services(NewRepoRegistry, NewUserService).
    RouterMiddlewares(requestid.New()).
    Middlewares().
    API("/users", NewUserAPI).
    API("/admin", basicauth.Default(creds), NewAdminAPI).
    Build().
    Listen(":8080")

Builder step order: Prefix/NoPrefix → AllowOrigin/Cors → Compression → LogRequests/LogRequestsWith → Health/NoHealth → Errors → Deferrables → Services → RouterMiddlewares/Middlewares → API → Build

Services implementing iris.Initializer (Init(ctx context.Context) error) are initialized once inside Build(), after dependency injection. Services implementing iris.Worker (Run(ctx) error / Stop(ctx) error) are started after the initializers and stopped by Shutdown, in registration order with the other closers. Shutdown waits for Run to return.

See architecture-and-patterns.md for full details.

Controller Pattern

type UserAPI struct {
    service UserService
}

func NewUserAPI(service UserService) *UserAPI {
    return &UserAPI{service: service}
}

func (api *UserAPI) Routing(r iris.Router) {
    r.Get("/", api.list)
    r.Post("/", api.create)
    r.Get("/{id:uuid}", api.getByID)
    r.Put("/{id:uuid}", api.update)
    r.Delete("/{id:uuid}", api.delete)
}

Built-in controllers ship in the controller/ package: FileServer (controller/fileserver), MVC (controller/mvc), APIGraph (controller/apigraph), Sitemap (controller/sitemap).

mvc.UseController[*C](opts...) and mvc.UseRepository(repo, opts...) both generate the six resource routes and both take mvc.Guard, mvc.Without, mvc.IDParam, mvc.BeforeWrite and mvc.Pagination. UseRepository needs no controller type at all: the repository's five methods over a standard context.Context are the whole resource.

Layered Architecture

Handler/Controller -> Service -> Repository -> Domain

Register services via Services() in the builder. Controllers receive them through constructor injection.

Core Concepts

ConceptType/SignatureDescription
Handlerfunc(iris.Context)Request handler function
Contextiris.Context (alias for *context.Context)Request/response object
Routeriris.RouterRoute group interface
Controlleriris.ControllerInterface with Routing(iris.Router) method
Optionsiris.OptionsApplication configuration
Configuratoriris.ConfiguratorInterface for configuring the app
Mapiris.MapAlias for map[string]any

Routing

HTTP methods: Get, Post, Put, Delete, Patch, Head, Options, Any, Handle

Path Parameter Macros

MacroExampleDescription
{name:string}/users/{name:string}String (default)
{id:int}/users/{id:int}Integer (all sizes: int8-64)
{id:uint}/users/{id:uint}Unsigned integer (uint8-64)
{id:uuid}/users/{id:uuid}UUID format
{active:bool}/filter/{active:bool}Boolean
{name:alphabetical}/org/{name:alphabetical}Letters only
{file:file}/assets/{file:file}Filename with extension
{rest:path}/files/{rest:path}Multi-segment wildcard
{email:email}/lookup/{email:email}Email address
{d:date}/report/{d:date}Date (YYYY/MM/DD)
{day:weekday}/schedule/{day:weekday}Day of week

Constraints: min(n), max(n), range(min,max), regexp(expr), prefix(s), suffix(s), contains(s), else 400

r.Get("/users/{id:int min(1) else 400}", handler)
r.Get("/files/{path:path}", handler)

See routing-and-macros.md for full reference.

Error Handling

Use the rest/errors package with canonical error codes:

CodeHTTP StatusUsage
errors.InvalidArgument400Bad client input
errors.NotFound404Resource not found
errors.Unauthenticated401Missing/invalid credentials
errors.PermissionDenied403Insufficient permissions
errors.AlreadyExists409Duplicate resource
errors.Internal500Server error
errors.ResourceExhausted429Rate limited
errors.BadGateway502An upstream this service depends on failed

Key methods:

errors.NotFound.Detail(ctx, "user not found", "no user with id 123")
errors.Internal.Err(ctx, err)              // Log error, send generic message
errors.Internal.LogErr(ctx, err)           // Log + send error response
errors.InvalidArgument.Data(ctx, "bad input", dataMap)
errors.InvalidArgument.Validation(ctx, validationErrors...)
errors.InvalidArgument.Message(ctx, "custom message")

Error mapping in builder:

Errors(errors.NewOptions().
    MapErrors(errors.NotFound, sql.ErrNoRows).
    MapErrors(errors.InvalidArgument, ErrValidation).
    MapErrorFunc(errors.Internal, func(err error) error { ... }).
    MapErrorContains(errors.InvalidArgument, "violates check constraint", "invalid value"))

// Typed: a generic method, E inferred from the function.
opts.MapErrorAs(errors.ResourceExhausted, func(e *QuotaError) *errors.Error { ... })

errors.NotFoundID(ctx, "plan", id) renders NOT_FOUND with the detail "plan <id> not found"; it always returns false (the Context.OK convention), the opposite of HandleError.

See error-handling.md for full reference.

REST Response Helpers

The Context helpers combine the success response and error mapping into one call. Each returns false when it wrote an error response instead.

ctx.OK(resp, err)            // 200 JSON, or mapped error response
ctx.Created(resp, err)       // 201 JSON, id scalars wrapped as {"id": ...}
ctx.NoContent(modified, err) // 204 when modified, 304 when not
ctx.Count(n, err)            // 200 {"count": N}, zero included
ctx.List(items, err, tolerate...) // 200 JSON array; nil and empty both render []
ctx.JSONOrError(resp)        // JSON now, with encode failures rendered as errors
ctx.Paginated(collectFunc, opts...) // paginated list responses; iris.AllowSort/DenySort
ctx.HandleError(err)         // the error branch alone, for a step with no success body
errors.Unavailable.Handle(ctx, err) // same, forcing the code instead of mapping it

See rest-helpers.md for full reference.

Context API

Request Reading

The Bind* family is what handlers call: it decodes, validates and writes the 4xx itself. The Read* family below is the layer under it, for a target the binder cannot produce.

ctx.BindJSON[T]()          // JSON body, validated; false means the 4xx was sent
ctx.BindJSONOptional[T]()  // same, but an empty body yields the zero T
ctx.BindParam[T]("id")     // one path parameter, typed
ctx.BindParams[T]()        // every path parameter, into a struct
ctx.ReadJSON(&v)           // JSON body
ctx.ReadXML(&v)            // XML body
ctx.ReadYAML(&v)           // YAML body
ctx.ReadForm(&v)           // Form data
ctx.ReadQuery(&v)          // Query parameters: `url` tag, else the `form` tag
ctx.ReadBody(&v)           // Auto-detect content type
ctx.ReadProtobuf(&v)       // Protobuf binary
ctx.ReadMsgPack(&v)        // MsgPack binary
ctx.Params().Get("id")     // Path parameter
ctx.Query().Get("key")     // Query parameter
ctx.Params().GetUUID("id") // also GetDuration, GetTime, GetIP on Params/Query/Form; zero value on a miss
ctx.BindUpdate[T]()        // JSON body + the validated ?columns= list
ctx.QueryDate("from", iris.QueryRequired()) // strict readers: a bad value is a 400
ctx.QueryDate("date day from")             // space-separated keys, tried in order
ctx.QueryInt("limit", iris.QueryDefault("25"))
ctx.QueryBool("detailed")
ctx.Header("key")          // Request header (ResponseHeader reads response headers)
ctx.Body()                 // Raw body bytes
ctx.FormFile("upload")     // File upload

Response Writing

The response helpers above (ctx.OK, ctx.Created, ctx.NoContent, ctx.Count, ctx.List, ctx.Paginated) carry the status and the error branch. These writers are what they are built on.

ctx.JSON(v)                // JSON response
ctx.XML(v)                 // XML response
ctx.YAML(v)                // YAML response
ctx.HTML("<h1>Hi</h1>")   // HTML response
ctx.Markdown([]byte("# Title"))
ctx.Text("plain text")    // Plain text
ctx.MsgPack(v)             // MsgPack binary
ctx.Protobuf(v)            // Protobuf binary
ctx.StatusCode(iris.StatusCreated)
ctx.SetHeader("key", "val")
ctx.Redirect("/path", iris.StatusFound)
ctx.SendFile("path/to/file", "download.pdf")
ctx.RenderComponent(component)

Request-Scoped Values

ctx.Values().Set("key", value)
ctx.Values().Get("key")
ctx.SetUser(user)
ctx.User()

See context-api.md for full reference.

Middleware

PackageDescription
accesslogStructured request/response logging (JSON, CSV, template)
apikeyShared-secret authentication for services, cron jobs and webhook senders
basicauthHTTP Basic Authentication with flexible backends
bodylimitRequest body size limits
cacheHTTP caching headers, ETag, Cache-Control
compressGzip/Brotli/Deflate response compression
corsCross-Origin Resource Sharing
counterRequest counter metrics
geolocationIP-based geolocation
grpcgRPC integration
hcaptchahCaptcha verification
httpcostRequest cost tracking
i18nInternationalization and localization
ipaccessIP allowlist/blocklist
jwtJSON Web Token auth (sign, verify, blocklist)
methodoverrideHTTP method override via header/form
modrevisionBuild info / health endpoint
monitorApplication monitoring
pprofGo profiling endpoints
rateToken bucket rate limiting
recaptchaGoogle reCAPTCHA verification
recorderResponse recorder for middleware chains
recoveryPanic recovery with stack traces
referrerReferrer tracking and parsing
requestidUnique request ID generation
rewriteURL rewriting rules
servertimingServer-Timing header
sessionsServer-side sessions (cookie, PostgreSQL, Redis)
versioningAPI versioning (header, query, subdomain)
viewTemplate engine integration
websocketWebSocket via neffos library

Global middleware (all requests including 404s): app.UseRouter(handler) or RouterMiddlewares(...) Route middleware (matched routes only): app.Use(handler) or Middlewares(...)

See middleware-reference.md for full reference.

Authentication SDK

The auth/ package provides a complete authentication and identity system:

  • JWT Authentication: EdDSA-signed access + refresh tokens
  • Identity Server: User management with PostgreSQL, OAuth2, 2FA
  • RBAC: Resource-action policies and scope validation
  • Session Management: Secure cookie storage with AES-GCM encryption
  • OAuth2: Authorization Code, Device Code, Password Grant flows
  • Client SDK: Multi-language identity SDK for consuming the auth API
  • Request scope: auth.Scope(derive) after VerifyHandler derives a tenant id once; auth.ScopeID[ID](ctx) reads it. A missing user, or one of another type, is a 401 (auth.ErrMissingUser); a derived zero id is stored as it is

See authentication-sdk.md for full reference.

HTTP Client

The client/ package provides the HTTP client for outbound calls from your services. See http-client.md for full reference.

Testing

func TestAPI(t *testing.T) {
    app := iris.NewBuilder().
        // ... builder config ...
        Build()

    e := httptest.New(t, app)
    e.GET("/api/users").Expect().Status(httptest.StatusOK).
        JSON().Array().NotEmpty()
    e.POST("/api/users").WithJSON(user).Expect().Status(httptest.StatusCreated)
}

Key functions:

  • httptest.New(t, app, ...options) - Create test client from app
  • httptest.NewController(t, prefix, controller, mw...) - A throwaway app around one controller, which is what Routing values need
  • httptest.NewInsecure(t, ...options) - Test running TLS servers
  • httptest.Do(w, r, handler) - Test individual handlers

See testing-guide.md for full reference.

Configuration and Deployment

  • Options: iris.Options{Name, LogLevel, Host, Router, Context}
  • YAML config: iris.New(iris.YAML("config.yml"))
  • Environment: opts.Bind("config.yml") checks SERVER_CONFIG env var first
  • Whole-service config: iris.LoadConfiguration[T](envKey, filename) with iris.BaseConfiguration embedded inline; the variable may hold the document or a path to it, BindEnv() runs after decoding, and c.Addr() feeds app.Listen. There is no app.Serve
  • Server: app.Listen(":8080") or app.Run(iris.ServerOptions{...}), called as statements: both block, return nil after a graceful shutdown once app.Shutdown has run its whole list of closers (the server's drain is the first of them, so a main that ends with Listen cuts neither a request nor a closer), and on a failed start log at fatal level and exit with status 1. iris.Options{DisableFatalRun: true} logs at error level and returns the error instead (several servers in one process, or a test with a real listener)
  • TLS: Certificate files, custom tls.Config, or automatic Let's Encrypt
  • Tunneling: Ngrok (NgrokOptions, opt-in: needs import _ "github.com/kataras/iris/v14/core/server/ngrok" or the server refuses to start) or SSH reverse tunnel
  • Graceful shutdown: app.Shutdown(ctx) drains the server, then runs the closers (AddCloser, Deferrables, a service's Close). A signal alone drains the server and exits without them; iris.RegisterOnInterrupt(app.Shutdown) runs the whole list on SIGINT/SIGTERM, within Timeout.ShutdownOnInterruptTimeout (15s by default, zero or negative for no deadline). That is one deadline for the drain and the closers together, counted from the signal, and an interrupt function that returns an error ends the process with status 1. A closer or an interrupt function that waits for Run or Listen to return blocks for good. A program with its own signal.Notify sets ServerOptions.DisableInterruptHandler: true
  • Build info: iris.PrintBuildInfo(w), iris.Version, iris.BuildRevision

See configuration-and-deployment.md for full reference.

Streaming and AI

sse.Open(ctx) writes nothing: the protocol headers commit on the first Send, so a check that fails after opening still returns an ordinary status code. That first Send removes buffering middleware, clears the server's absolute WriteTimeout and sets the anti-buffering headers. Close writes the terminal frame on success too, so its absence is how a client detects truncation. sse.Read consumes an upstream stream as an iter.Seq2. Timeout.HandlerTimeout makes streaming impossible, which is what sse.ErrNotStreamable reports.

ai.Open(ctx, opts) serves the streaming and the non-streaming shape from one handler (Options.Stream is a *bool, so nil negotiates on Accept). Seven Part kinds, three neutral encoders, ai.Relay with a Decoder you write, and ai.Classify(resp, err) for a typed *ai.UpstreamError whose Class says whether to retry, switch credential or stop. Never retry after Committed().

A failure after the first byte cannot be rendered, so it goes out as an error frame. errors.Report(ctx, err) runs the rest/errors pipeline (mapping, logging, collection, id, redaction) and returns the *Error without writing it, which is what sse.Options.ErrorFrame defaults to. Never forward a provider's own message to your caller: (*ai.UpstreamError).Report(ctx) logs it and gives the client a canonical code instead.

See sse.md and ai.md for full reference.

Migrating from v12

v14 renamed a lot. The traps that compile fine but misbehave, or that the model most often gets wrong:

v12v14
iris.Party, app.Party, PartyFunciris.Router, app.Router
Configure(r iris.Party)Routing(r iris.Router)
ctx.URLParam* (whole family)ctx.Query().Get*
ctx.Header("k", "v") (set)ctx.SetHeader("k", "v")
ctx.GetHeader("k") (read request)ctx.Header("k")
iris.Configuration, With*iris.Options, iris.Defaults
app.RegisterView, ctx.Viewview.Handler(engine), view.Render(ctx, ...)
app.OnErrorCodeapp.HandleNoRoute, HandleNoMethod, Errors(...)

Security defaults also changed (session cookies Secure+Lax, JWT header-only, no wildcard CORS credentials). See migration-v12-to-v14.md.

Security

v14 is secure by default in most places, with two deliberate gaps: Iris ships no CSRF middleware and injects no security headers. Two permissive defaults worth flipping: ContextOptions.BodyMaxMemory is 0 (unlimited), and the file server serves dotfiles.

iris.Options{Context: iris.ContextOptions{BodyMaxMemory: 10 * iris.MB}}
fileserver.Options{AssetValidator: fileserver.BlockHidden}

See security-hardening.md for full reference.

Database

No ORM. Register the store through Services(...) and the builder handles the lifecycle: a Close() method becomes a shutdown closer, and Init(ctx) error (iris.Initializer) runs inside Build() after DI. Translate driver errors to domain sentinels at the store boundary, then map those once in Errors(...). With github.com/kataras/pg, add import _ ".../rest/errors/pgerrors" to keep 404/409 mapping.

See database-and-persistence.md for full reference.

Caching

Three layers: middleware/cache writes headers (its validators are clock-derived, not content-derived), middleware/cache/httpcache stores responses in Redis/DragonflyDB with Pair-based invalidation, and core/pkg/cache is an in-process map. Identity must be in the cache key (Headers, Cookies) or do not response-cache the route. httpcache never stores a response whose Cache-Control carries private, no-store or no-cache, also when a middleware ahead of it set the header. A request that carries Authorization, Proxy-Authorization or cookies is cached only when the key includes every one of them (the header in Headers, each cookie it sends in Cookies); a credential in a custom header is invisible to that check until Headers names it. With sessions, register the cache handler before sessions.Handler: after it, the page made for a new session is stored before the session cookie is written. Behind a reverse proxy that caches, send Cache-Control: private on every page that depends on a session, because a request that only reads the session gets no Set-Cookie.

See caching.md for full reference.

Internationalization

middleware/i18n needs no third-party dependency. NewRouter on UseRouter strips a language path prefix or subdomain before routing; NewHandler on Use resolves the locale. Then i18n.GetMessage(ctx, key, args...).

See i18n.md for full reference.

Observability

middleware/accesslog on UseRouter (so 404s are logged) with Async = true and bodies off. Add requestid before it. Gate monitor and pprof behind auth. Two notes: the monitor's RefreshInterval defaults to monitor.DefaultRefreshInterval (2 seconds) when unset, and httpcost writes its metric only after the chain returns.

See observability.md for full reference.

Performance

The framework already pools contexts, stores params in slices rather than maps, and resolves routes through prefix trees built at startup. Do not rebuild those. The hard rule: never retain iris.Context past the handler's return; pass ctx.StdContext() to consumers that keep the context (HTTP clients, database drivers) and use ctx.WithoutCancel() for background work. For large payloads use ctx.StreamWriter, ctx.ReadJSONStream and ctx.Paginated.

See performance.md for full reference.

Key File Paths

AreaPath
Applicationiris.go, iris_builder.go, aliases.go, options.go
Contextcontext/context.go
Routercore/router/
Errorsrest/errors/
REST helpersrest/ (response helpers; rest/errors/ for canonical codes)
HTTP clientclient/
Built-in controllerscontroller/ (FileServer, MVC, APIGraph, Sitemap)
Scalar payload typesrest/types/ (dates, durations, Number, Weekday)
Multi-app registryapps/
Middlewaremiddleware/*/
Authauth/, auth/identity/, auth/oauth2/
Streamingsse/ (transport), ai/ (model streams, relays, classification)
Testinghttptest/
Servercore/server/
Bookkataras/iris-book (24 chapters, separate repository)
TutorialTUTORIAL.md (repo root), references/getting-started-tutorial.md
MigrationMIGRATION.md (repo root), HISTORY.md
Examples_examples/ (16 numbered topic dirs; 01-getting-started is a 13-step tutorial, then 02-routing … 16-advanced)

Conventions

  • Constructors: NewXxx returning interface or pointer; used for DI
  • Controller receivers: (api *XxxAPI) or (c *XxxController)
  • Error handling: Use rest/errors canonical codes, not raw HTTP status codes
  • DI: Register services in builder's Services(), consumed by controller constructors
  • Middleware: Always call ctx.Next() to continue the chain
  • Response methods: ctx.JSON(), ctx.XML(), ctx.HTML(), etc.
  • Query and path params: Read query parameters via ctx.Query() and path parameters via ctx.Params(); both return typed entries with direct accessors (Get, GetInt64, GetBool, etc.), no tuple returns
  • Byte sizes: Use iris.B, iris.KB, iris.MB, iris.GB constants
  • Context as context.Context: iris.Context implements context.Context; pass directly to calls that return before the handler does. Never retain it past the handler's return: it is pooled. Pass ctx.StdContext() to HTTP clients and anything else that keeps the context; use ctx.WithoutCancel() for background work
  • Route groups: Use r.Router("/sub", controllers...) for nested groups
  • Request headers: ctx.Header(k) reads the request, ctx.ResponseHeader(k) reads the response, ctx.SetHeader(k, v) replaces and ctx.AddHeader(k, v) appends. There is no GetHeader
  • Validation: Give the request type a Validate() error; ctx.BindJSON runs it and renders the 400 for you

Sponsors

Details

Marketplace
kataras/iris
Source
.
Category
Community