iris

package module
v14.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 12, 2026 License: BSD-3-Clause Imports: 31 Imported by: 0

README ΒΆ

Iris Web Framework

build status release view examples godocs chat donate

Iris is a fast, batteries-included web framework for Go. It gives your next API or website expressive routing with typed path parameters, one place for error handling, dependency injection that keeps code testable, and production defaults that are secure out of the box.

Version 14 is the largest release in the project's history. The framework was rebuilt around Go generics: a compile-enforced application builder, typed request helpers that validate for you, controllers resolved by the dependency container, and an error pipeline you configure once. HISTORY.md records everything new; the Migration Guide brings v12 applications forward in one sitting.

πŸ€– Ask AI about Iris. Google's free Code Wiki for Iris is generated from this repository and stays in sync with it, commit by commit. Browse the architecture with diagrams, or ask its chat plain-language questions about the codebase and get answers grounded in the actual source. For an assistant that writes Iris code with you, Plexon AI, the desktop assistant built by the author of Iris, ships the Iris skill built in. The same skill installs into Claude Code as a plugin; see AI Tools for Iris below.

Learn what others say about Iris and star this open-source project to support its development. Curious about speed? See the server benchmarks.

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.Get("/greet/{name:string}", func(ctx iris.Context) {
        ctx.WriteString("Hello, " + ctx.Params().GetString("name"))
    })

    app.Listen(":8080")
}
The production stack, in one expression

Real applications use iris.NewBuilder: a compile-enforced chain that wires CORS, compression, access logs, a health endpoint, your error map, your services and your API groups. The compiler rejects wrong step order.

iris.NewBuilder().
    Prefix("/api").
    AllowOrigin("*").
    Compression(true).
    LogRequests(true).
    Health(true, "production", "kataras").
    Errors(errors.NewOptions().
        MapErrors(errors.NotFound, catalog.ErrNotFound)).
    Services(catalog.NewRepository, catalog.NewService).
    RouterMiddlewares().
    Middlewares().
    API("/products", api.NewProductsAPI).
    Build().
    Listen(":8080")

Handlers stay six lines long, because decoding, validation and error rendering happen in one configured place:

func (api *ProductsAPI) create(ctx iris.Context) {
    input, ok := ctx.BindJSON[catalog.ProductInput]()
    if !ok {
        return // 400 already written: malformed JSON or failed Validate.
    }

    id, err := api.svc.Create(ctx, input)
    ctx.Created(id, err) // 201, or the centrally mapped error.
}

The Getting Started Tutorial builds a complete, tested service on this stack in one document.

As one Go developer once said, Iris got you covered all-round and standing strong over the years.

What you get with Iris v14:

  • Routing with typed path parameters ({id:uuid}, {n:int}, {addr:email} and more), custom macros and constraints. Invalid input is rejected before your handler runs.
  • iris.NewBuilder: CORS, compression, access logging, health endpoint, error mapping, services and API groups assembled in one compile-checked chain.
  • Dependency injection: constructors declare what they need, the container provides it. Startup Initializer hooks, automatic shutdown closers.
  • The rest helpers and one central error map: thin handlers, canonical machine-readable errors, internals never leak to clients.
  • Request payloads that validate themselves: implement Validate() error and ctx.BindJSON runs it after decoding.
  • Thirty-one built-in middleware: accesslog, API keys, basicauth, bodylimit, cache, CORS, hCaptcha and reCAPTCHA, JWT, monitor, pprof, rate limiting, recovery, request IDs, rewrite, sessions, versioning and more.
  • Authentication at every scale: one-line Basic Auth, API keys, a generic JWT SDK, a complete identity server and an OAuth2 provider.
  • MVC controllers built on Go generics.
  • WebSockets, gRPC serving and API versioning.
  • View engines: HTML, Django, Handlebars, Pug and more through iris-contrib/views.
  • Localization with pluralization and language detection, plus sitemaps.
  • Sessions with secure cookie defaults (Secure, SameSite=Lax out of the box).
  • Rich responses: JSON, JSONP, XML, YAML, Markdown, Protocol Buffers, MessagePack, content negotiation, streaming and Server-Sent Events.
  • AI backends: the ai package renders and relays streamed model output over HTTP (text deltas, reasoning traces, tool-call fragments, usage). It is provider-agnostic and ships no vendor SDK.
  • An HTTP client, the client package, for calling other services under the same JSON rules the server side uses.
  • Response compression: gzip, deflate, brotli, snappy, s2, zstd.
  • TLS with Let's Encrypt, and ngrok tunneling, one blank import of core/server/ngrok away, to put a dev app on the internet in seconds.
  • In-memory HTTP testing: full-application tests with no ports, no network and no sleeps.
  • A complete book that is free to read online and to download, a hands-on tutorial and a live AI wiki (see Learning Iris below).
  • And the most important: you get fast answers and support, from the first day until now.

πŸ‘‘ Supporters

With your help, we can improve Open Source web development for everyone!

getsentry github lensesio thepunterbot AGPDev centratelemedia odelanno zou8944 draFWM gf3 trading-peter AlbinoGeek basilarchia sumjoe simpleittools xiaozhuai Remydeme celsosz linxcoder jnelle TechMaster janwebdev altafino jakoubek alekperos day0ng hengestone thomasfr CetinBasoz International Juanses SometimesMage ansrivas boreevyuri ekobayong lexrus li3p madhu72 se77en tstangenberg vincent-li sascha11110 clichi2002 derReineke Sirisap22 primadi agoncecelia antonio-pedrazzini chrisliang12 zyu hobysmith pluja clacroix njeff3 ixalender mubariz-ahmed Cesar DavidShaw th31nitiate stgrosshh rodrigoghm Didainius DmarshalTU IwateKyle Little-YangYang Major2828 MatejLach amritpal042 andrefiorot boomhut cshum dtrifonov geordee guanting112 iantuan ichenhe icibiri jewe11er jfloresremar jingtianfeng kilarusravankumar leandrobraga lfbos lpintes macropas marcmmx mark2b miguel-devs mihado mmckeen75 narven odas0r olaf-lexemo pitexplore pr123 rsousacode sankethpb saz59 shadowfiga siriushaha spazzymoto victorgrey ArishSultan ehayun kukaki oshirokazuhide t6tg 15189573255 AnatolyUA AwsIT BlackHole1 FernandoLangOFC Firdavs9512 Flammable-Duck Hongjian0619 JoeD Jude-X Kartoffelbot KevinZhouRafael KrishManohar Laotanling Longf99999 Lyansun MihaiPopescu1985 skurtz97 srinivasganti syrm tuhao1020 wahyuief xvalen xytis ElNovi IpastorSan KKP4 Lernakow Mohammed8960 NA Neulhan NguyenPhuoc Oka00 ernestocolombo francisstephan pixelheresy rcapraro soiestad thanasolykos ukitzmann DanielKirkwood colinf simonproctor TBNilles ajanicij aprinslo1 kyoukhana PaddyFrenchman RainerGevers Ramblestsad SamuelNeves Scorpio69t Serissa4000 TianJIANG Ubun1 XinYoungCN YukinaMochizuki a112121788 acdias aeonsthorn agent3bood alessandromarotta algoflows angelaahhu anhxuanpham annieruci antoniejiao artman328 b2cbd baoch254 bastengao beytullahakyuz bjoroen blackHoleNgc1277 bunnycodego carlos-enginner chrismalek civicwar cnzhangquan cuong48d damiensy danlanxiaohei dfaugusto dkzhang dloprodu donam-givita dph0899 ec0629 edwindna2 ekofedriyanto eli-yip eljefedelrodeodeljefe fenriz07 ffelipelimao frenchmajesty gastropulgite geGao123 globalflea gloudx gnosthi gogoswift goten002 guanzi008 hdezoscar93 hieungm hieunmg homerious hzxd iuliancarnaru iysaleh jackptoke jackysywk jeff2go jeremiahyan joelywz kamolcu kana99 kattaprasanth keeio keval6706 keymanye khasanovrs kkdaypenny knavels kohakuhubo korowiov kostasvk lafayetteDan lbsubash leki75 lemuelroberto liheyuan lingyingtan linuxluigi lipatti maikelcoke marek-kuticka marman-hp mattbowen maxgozou maxgozzz mizzlespot mkell43 mnievesco mo3lyana motogo mtrense mukunhao mulyawansentosa nasoma ngseiyu nikharsaxena nronzel onlysumitg ozfive paulxu21 pesquive petros9282 phil535 pitt134 qiepeipei qiuzhanghua rapita rbondi relaera remopavithran rfunix rhernandez-itemsoft rikoriswandha risallaw robivictor rubiagatra rubyangxg rxrw saleebm sbenimeli sebyno seun-otosho solohiroshi su1gen sukiejosh svirmi terjelafton thiennguyen93 unixedia vadgun valsorym vguhesan vpiduri vrocadev vuhoanglam walter-wang wixregiga yesudeep ymonk yonson2 yshengliao yusong-offx zhenggangpku SergeShin - BelmonduS Diewald cty4ka xPoppa martinjanda martinlindhe mdamschen netbaalzovf oliverjosefzimmer talebisinan valkuere lfaynman ArturWierzbicki Supersherm5 aaxx crashCoder derekslenk dochoaj edsongley evillgenius75 gog200921 mauricedcastro mwiater sj671 statik supersherm5 thejones CSRaghunandan GeorgeFourikis L-M-Sherlock claudemuller vcruzato evan hazmi-e205 jtgoral ky2s lauweliam letmestudy mblandr midhubalan ndimorle rosales-stephanie shyyawn wangbl11 wofka72 yoru74 xsokev oleang michalsz michaelsmanley Curtman SridarDhandapani opusmagna ShahramMebashar b4zz4r bobmcallan fangli galois-tnp geoshan juanxme nguyentamvinhlong pomland-94 tejzpr theantichris tuxaanand raphael-brand willypuzzle malcolm-white-dti HieuLsw carlosmoran092 yangxianglong

πŸ“– Learning Iris

New to Iris? Start with the Getting Started Tutorial: one document that takes you from go mod init to a tested, production-shaped REST API. Upgrading from v12? See the Migration Guide. Questions at any point? Ask the free live AI wiki at codewiki.google/github.com/kataras/iris. Google generates it from the Iris source and keeps it in sync, and its built-in chat answers questions about the codebase.

Installation

The only requirement is the Go Programming Language, version 1.27 or later.

Create a new project
$ mkdir myapp
$ cd myapp
$ go mod init myapp
$ go get github.com/kataras/iris/v14@latest # or @v14.0.0
Install on existing project
$ cd myapp
$ go get github.com/kataras/iris/v14@latest

Run

$ go mod tidy
$ go run .

Iris contains extensive and thorough documentation making it easy to get started with the framework.

For a more detailed technical documentation you can head over to our godocs. For a complete, hands-on introduction to the recommended v14 stack read the Getting Started Tutorial, and if you are upgrading from v12 follow the Migration Guide.

Prefer learning from code? The 78 examples start with a thirteen-step tutorial that grows one service from a single route to a tested, production-shaped API, then cover every topic in the order the book teaches it: routing, controllers, requests, responses, middleware, dependency injection, errors, authentication, configuration, views, databases, websockets, testing, production and the framework's extension points. Every one of them was compiled and exercised over HTTP before it was committed.

The Iris Book

Book cover

A preface, 24 chapters and an epilogue, every code example verified against the framework source. Each chapter opens with a plain-language background for newcomers and closes with curated further reading. Every chapter is free to read online; the book page has the full table of contents.

The PDF is free too. Download it directly: there is no form to fill in and nothing to request. If the book helps you, sponsoring the project is how you take part in the development of Iris.

follow author on twitter

follow Iris web framework on twitter

follow Iris web framework on facebook

πŸ€– AI Tools for Iris

Two AI tools know this framework specifically, beyond what a general model knows about Go.

The live AI wiki is free and runs in your browser: browse the architecture, or ask its chat about the codebase.

Plexon AI is a desktop assistant for Windows, macOS and Linux, built by the author of Iris. It ships the Iris skill built in: the v14 API, the builder chain, the rest helpers, error mapping, the auth SDK and the testing patterns, in twenty-one reference documents the assistant loads on demand while it writes your code. Turn the skill on from the Skills panel, or install the Software Developer persona, which enables it together with the rest of its engineering tooling. Download Plexon AI.

Claude Code

This repository is also a plugin marketplace, so the CLI can install the same skill and update it in place:

$ claude plugin marketplace add kataras/iris
$ claude plugin install iris@kataras-iris

The same pair works as slash commands inside a session (/plugin marketplace add kataras/iris, then /plugin install iris@kataras-iris). Later:

$ claude plugin marketplace update kataras-iris   # pull newer versions
$ claude plugin details iris                      # what it contains and its token cost
$ claude plugin uninstall iris                     # remove it

--scope user is the default. Pass --scope project to record the install in the current project instead, so your team picks it up from your repository.

The plugin ships one skill and nothing else: no commands, no agents, no hooks, no MCP servers. Installing it cannot change how Claude Code behaves outside of Iris work.

To try a change from a checkout before installing it, point a session at the folder for that session only:

$ claude --plugin-dir /path/to/iris

Without the plugin machinery, copy the skill folder into your skills directory instead. Personal, available in every project:

$ npx degit kataras/iris/skill/iris ~/.claude/skills/iris

Project-scoped:

$ npx degit kataras/iris/skill/iris .claude/skills/iris

This route works for any assistant that reads Markdown instructions, not only Claude Code: point your agent configuration at skill/iris/SKILL.md, and it loads the reference document that matches the task at hand. It has no version tracking, which is the trade-off against the plugin install above.

πŸ™Œ Contributing

We'd love to see your contribution to the Iris Web Framework! For more information about contributing to the Iris project please check the CONTRIBUTING.md file.

List of all Contributors

πŸ›‘ Security Vulnerabilities

If you discover a security vulnerability within Iris, please send an e-mail to iris-go@outlook.com. All security vulnerabilities will be promptly addressed.

πŸ“ License

This project is licensed under the BSD 3-clause license, just like the Go project itself.

The project name "Iris" was inspired by the Greek mythology.

Documentation ΒΆ

Overview ΒΆ

Package iris is a web framework for Go.

It gives you routing with typed path parameters, dependency injection that keeps handlers testable, one place to map every error your application returns, and defaults that are safe to run in production. Handlers are plain functions over a pooled Context. After Application.Build the application is an ordinary http.Handler, so anything that speaks net/http still fits around it.

Source code and other details for the project are available at GitHub:

https://github.com/kataras/iris

Installation ΒΆ

The only requirement is the Go Programming Language, version 1.27 or later.

$ go get github.com/kataras/iris/v14@latest

The release you are running is the Version constant. HISTORY.md records what changed in each one and MIGRATION.md covers the upgrade from v12, which is the largest break in the project's history.

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.Get("/greet/{name:string}", func(ctx iris.Context) {
		ctx.WriteString("Hello, " + ctx.Params().GetString("name"))
	})

	app.Listen(":8080")
}

Default returns the same application with a debug logger, permissive CORS, panic recovery and request IDs already registered. Use it while you explore, not in production.

Application Setup ΒΆ

There are three ways in. New builds a bare application that you configure yourself. Default pre-registers the middleware above. NewBuilder is the one to reach for in production: the steps return narrowing interfaces, so the compiler rejects a chain written in the wrong order.

app := iris.NewBuilder().
	Prefix("/api").
	AllowOrigin("*").
	Compression(true).
	LogRequests(true).
	Health(true, "production", "you@example.com").
	Errors(errors.NewOptions().
		MapErrors(errors.NotFound, sql.ErrNoRows)).
	Services(catalog.NewRepository, catalog.NewService). // your constructors
	RouterMiddlewares().
	Middlewares().
	API("/products", api.NewProductsAPI). // your controller
	Build()

app.Listen(":8080")

Configuration lives in Options, which is itself a Configurator, so a partial literal sets only the fields you name. Defaults takes edit callbacks, YAML reads a file, and Options.Bind reads the SERVER_CONFIG environment variable. Application.EditOptions changes them after construction.

Application.Listen serves HTTP on an address. Application.Run takes ServerOptions when you need TLS, a custom tls.Config or a prepared listener. Application.Shutdown drains connections, and RegisterOnInterrupt wires it to Ctrl-C.

Routing ΒΆ

Path parameters carry a type, and a request whose parameter does not match is rejected before your handler runs:

app.Get("/products/{id:uuid}", show)
app.Get("/users/{age:int min(18)}", create)
app.Get("/assets/{file:path}", download)

The built-in macros are string, int and its sized forms, uint and its sized forms, bool, alphabetical, file, path, uuid, uuidv4, mail, email, date and weekday. Each accepts constraint functions such as min, max and regexp. Register your own through app.Macros().

Group routes with app.Router("/prefix"). For controllers, implement Routing and let the dependency container resolve the constructor's arguments.

The Context ΒΆ

Context is an alias for *context.Context. One is acquired from a pool per request and released when the chain ends, so it must not be retained past the handler's return or used from another goroutine. Clone it first when you need to hand it to one.

The request side reads through Params, the Read family (ReadJSON, ReadForm, ReadQuery and friends) and RemoteAddr. The response side writes through JSON, Text, HTML, Negotiate and the cookie helpers. FromStd wraps an existing net/http handler; NewContextWrapper swaps in your own context type.

The full method set is documented in github.com/kataras/iris/v14/context.

Request Binding and Validation ΒΆ

ctx.BindJSON decodes the body into your type and, when that type has a Validate method, runs it. Both failures write the 400 for you, so a handler that gets ok == false has nothing left to do:

type CreateUserInput struct {
	Email string `json:"email"`
	Age   int    `json:"age"`
}

func (in *CreateUserInput) Validate() error {
	if in.Age < 18 {
		return errors.New("age must be 18 or older")
	}

	return nil
}

func create(ctx iris.Context) {
	input, ok := ctx.BindJSON[CreateUserInput]()
	if !ok {
		return // 400 already written.
	}

	id, err := users.Create(ctx, input)
	ctx.Created(id, err) // 201, or the centrally mapped error.
}

Set Options.Context.RequestValidator to run a validator after every decode regardless of type, and Options.Context.BodyMaxMemory to cap how much of a body any reader will accept.

See github.com/kataras/iris/v14/context for the full list of Context methods.

Error Handling ΒΆ

Register your error codes once and map your domain errors onto them. Responses follow RFC 7807, and an error you have not mapped renders as a generic 500 rather than leaking its message. Errors that implement ErrPrivate never reach the client at all.

See github.com/kataras/iris/v14/rest/errors, which documents the model in full.

Security Defaults ΒΆ

  • Uploads. UploadFormFiles runs every filename through SafeFilename, which rejects traversal, symlink escapes and reserved Windows device names such as NUL and COM1. A rejected file is skipped rather than saved. Call SafeFilename yourself if you write files through SaveFormFile instead.
  • JSONP. A callback is validated before it is written into the script response. An invalid one fails with context.ErrInvalidJSONPCallback rather than reflecting attacker-supplied script.
  • Client address. Context.RemoteAddr filters proxy headers against the private subnets you configure, and trusts no X- header until Options.Context.RemoteAddrHeaders names one. Context.Addr is the client's own unfiltered claim, so use it for logging and never for authorization.
  • Response headers. Context.SetHeader replaces, so a middleware registered twice cannot emit the duplicate that browsers reject. Context.AddHeader appends, for list-valued headers such as Vary.
  • Body size. Options.Context.BodyMaxMemory is off by default: 0 means no limit. Set it and every body reader is capped, answering 413 past the limit. Context.ContentLength reports -1 when the length is unknown, as it is for a chunked request, so enforce the limit rather than trusting the header.
  • Sessions and cookies. Session cookies default to Secure with SameSite=Lax, and Context.AddCookie defaults to SameSite=Lax.

SECURITY.md lists the opt-in hardening worth turning on, and MIGRATION.md explains each default that changed since v12.

Middleware ΒΆ

Middleware registered with UseRouter runs for every request, including the ones that match no route. Middleware registered with Use runs for matched routes only, and Done runs after the handler.

About thirty middleware ship with the framework, among them accesslog, basicauth, bodylimit, cache, cors, jwt, rate, recovery, requestid and sessions:

https://github.com/kataras/iris/tree/main/middleware
https://github.com/iris-contrib/middleware

Testing ΒΆ

The httptest package runs requests against your application in memory. No port is bound, no network is touched and nothing sleeps:

func TestIndex(t *testing.T) {
	app := newApp()

	e := httptest.New(t, app)
	e.GET("/").Expect().Status(httptest.StatusOK)
}

Learning Iris ΒΆ

Tutorial:

https://github.com/kataras/iris/blob/main/TUTORIAL.md

Examples:

https://github.com/kataras/iris/tree/main/_examples

Upgrading from v12:

https://github.com/kataras/iris/blob/main/MIGRATION.md

Frequently asked questions:

https://github.com/kataras/iris/blob/main/FAQ.md

Home Page:

https://www.iris-go.com
Example ΒΆ

Serve a request without binding a port, which is also how the httptest package runs your tests.

package main

import (
	"fmt"
	"net/http/httptest"

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

func main() {
	app := iris.New()

	app.Get("/greet/{name:string}", func(ctx iris.Context) {
		ctx.WriteString("Hello, " + ctx.Params().GetString("name"))
	})

	if err := app.Build(); err != nil {
		panic(err)
	}

	w := httptest.NewRecorder()
	app.Handler.ServeHTTP(w, httptest.NewRequest("GET", "/greet/gopher", nil))

	fmt.Println(w.Code)
	fmt.Println(w.Body.String())
}
Output:
200
Hello, gopher

Index ΒΆ

Examples ΒΆ

Constants ΒΆ

View Source
const (
	SameSiteDefaultMode = http.SameSiteDefaultMode
	SameSiteLaxMode     = http.SameSiteLaxMode
	SameSiteStrictMode  = http.SameSiteStrictMode
	SameSiteNoneMode    = http.SameSiteNoneMode
)

SameSite attributes.

View Source
const (
	// RouteOverride replaces an existing route with the new one, the default rule.
	RouteOverride = router.RouteOverride
	// RouteSkip keeps the original route and skips the new one.
	RouteSkip = router.RouteSkip
	// RouteError log when a route already exists, shown after the `Build` state,
	// server never starts.
	RouteError = router.RouteError
)

Constants for input argument at `router.RouteRegisterRule`. See `Router#SetRegisterRule`.

View Source
const (
	MethodGet     = http.MethodGet
	MethodPost    = http.MethodPost
	MethodPut     = http.MethodPut
	MethodDelete  = http.MethodDelete
	MethodConnect = http.MethodConnect
	MethodHead    = http.MethodHead
	MethodPatch   = http.MethodPatch
	MethodOptions = http.MethodOptions
	MethodTrace   = http.MethodTrace
	// MethodQuery is the RFC 10008 QUERY method.
	MethodQuery = router.MethodQuery
	// MethodNone is an iris-specific "virtual" method
	// to store the "offline" routes.
	MethodNone = router.MethodNone
)

HTTP Methods copied from `net/http`.

View Source
const (
	StatusContinue           = http.StatusContinue           // RFC 7231, 6.2.1
	StatusSwitchingProtocols = http.StatusSwitchingProtocols // RFC 7231, 6.2.2
	StatusProcessing         = http.StatusProcessing         // RFC 2518, 10.1
	StatusEarlyHints         = http.StatusEarlyHints         // RFC 8297

	StatusOK                   = http.StatusOK                   // RFC 7231, 6.3.1
	StatusCreated              = http.StatusCreated              // RFC 7231, 6.3.2
	StatusAccepted             = http.StatusAccepted             // RFC 7231, 6.3.3
	StatusNonAuthoritativeInfo = http.StatusNonAuthoritativeInfo // RFC 7231, 6.3.4
	StatusNoContent            = http.StatusNoContent            // RFC 7231, 6.3.5
	StatusResetContent         = http.StatusResetContent         // RFC 7231, 6.3.6
	StatusPartialContent       = http.StatusPartialContent       // RFC 7233, 4.1
	StatusMultiStatus          = http.StatusMultiStatus          // RFC 4918, 11.1
	StatusAlreadyReported      = http.StatusAlreadyReported      // RFC 5842, 7.1
	StatusIMUsed               = http.StatusIMUsed               // RFC 3229, 10.4.1

	StatusMultipleChoices  = http.StatusMultipleChoices  // RFC 7231, 6.4.1
	StatusMovedPermanently = http.StatusMovedPermanently // RFC 7231, 6.4.2
	StatusFound            = http.StatusFound            // RFC 7231, 6.4.3
	StatusSeeOther         = http.StatusSeeOther         // RFC 7231, 6.4.4
	StatusNotModified      = http.StatusNotModified      // RFC 7232, 4.1
	StatusUseProxy         = http.StatusUseProxy         // RFC 7231, 6.4.5

	StatusTemporaryRedirect = http.StatusTemporaryRedirect // RFC 7231, 6.4.7
	StatusPermanentRedirect = http.StatusPermanentRedirect // RFC 7538, 3

	StatusBadRequest                   = http.StatusBadRequest                   // RFC 7231, 6.5.1
	StatusUnauthorized                 = http.StatusUnauthorized                 // RFC 7235, 3.1
	StatusPaymentRequired              = http.StatusPaymentRequired              // RFC 7231, 6.5.2
	StatusForbidden                    = http.StatusForbidden                    // RFC 7231, 6.5.3
	StatusNotFound                     = http.StatusNotFound                     // RFC 7231, 6.5.4
	StatusMethodNotAllowed             = http.StatusMethodNotAllowed             // RFC 7231, 6.5.5
	StatusNotAcceptable                = http.StatusNotAcceptable                // RFC 7231, 6.5.6
	StatusProxyAuthRequired            = http.StatusProxyAuthRequired            // RFC 7235, 3.2
	StatusRequestTimeout               = http.StatusRequestTimeout               // RFC 7231, 6.5.7
	StatusConflict                     = http.StatusConflict                     // RFC 7231, 6.5.8
	StatusGone                         = http.StatusGone                         // RFC 7231, 6.5.9
	StatusLengthRequired               = http.StatusLengthRequired               // RFC 7231, 6.5.10
	StatusPreconditionFailed           = http.StatusPreconditionFailed           // RFC 7232, 4.2
	StatusRequestEntityTooLarge        = http.StatusRequestEntityTooLarge        // RFC 7231, 6.5.11
	StatusRequestURITooLong            = http.StatusRequestURITooLong            // RFC 7231, 6.5.12
	StatusUnsupportedMediaType         = http.StatusUnsupportedMediaType         // RFC 7231, 6.5.13
	StatusRequestedRangeNotSatisfiable = http.StatusRequestedRangeNotSatisfiable // RFC 7233, 4.4
	StatusExpectationFailed            = http.StatusExpectationFailed            // RFC 7231, 6.5.14
	StatusTeapot                       = http.StatusTeapot                       // RFC 7168, 2.3.3
	StatusMisdirectedRequest           = http.StatusMisdirectedRequest           // RFC 7540, 9.1.2
	StatusUnprocessableEntity          = http.StatusUnprocessableEntity          // RFC 4918, 11.2
	StatusLocked                       = http.StatusLocked                       // RFC 4918, 11.3
	StatusFailedDependency             = http.StatusFailedDependency             // RFC 4918, 11.4
	StatusTooEarly                     = http.StatusTooEarly                     // RFC 8470, 5.2.
	StatusUpgradeRequired              = http.StatusUpgradeRequired              // RFC 7231, 6.5.15
	StatusPreconditionRequired         = http.StatusPreconditionRequired         // RFC 6585, 3
	StatusTooManyRequests              = http.StatusTooManyRequests              // RFC 6585, 4
	StatusRequestHeaderFieldsTooLarge  = http.StatusRequestHeaderFieldsTooLarge  // RFC 6585, 5
	StatusUnavailableForLegalReasons   = http.StatusUnavailableForLegalReasons   // RFC 7725, 3
	// Unofficial Client Errors.
	StatusPageExpired                      = context.StatusPageExpired
	StatusBlockedByWindowsParentalControls = context.StatusBlockedByWindowsParentalControls
	StatusInvalidToken                     = context.StatusInvalidToken
	StatusTokenRequired                    = context.StatusTokenRequired
	//
	StatusInternalServerError           = http.StatusInternalServerError           // RFC 7231, 6.6.1
	StatusNotImplemented                = http.StatusNotImplemented                // RFC 7231, 6.6.2
	StatusBadGateway                    = http.StatusBadGateway                    // RFC 7231, 6.6.3
	StatusServiceUnavailable            = http.StatusServiceUnavailable            // RFC 7231, 6.6.4
	StatusGatewayTimeout                = http.StatusGatewayTimeout                // RFC 7231, 6.6.5
	StatusHTTPVersionNotSupported       = http.StatusHTTPVersionNotSupported       // RFC 7231, 6.6.6
	StatusVariantAlsoNegotiates         = http.StatusVariantAlsoNegotiates         // RFC 2295, 8.1
	StatusInsufficientStorage           = http.StatusInsufficientStorage           // RFC 4918, 11.5
	StatusLoopDetected                  = http.StatusLoopDetected                  // RFC 5842, 7.2
	StatusNotExtended                   = http.StatusNotExtended                   // RFC 2774, 7
	StatusNetworkAuthenticationRequired = http.StatusNetworkAuthenticationRequired // RFC 6585, 6
	// Unofficial Server Errors.
	StatusBandwidthLimitExceeded = context.StatusBandwidthLimitExceeded
	StatusInvalidSSLCertificate  = context.StatusInvalidSSLCertificate
	StatusSiteOverloaded         = context.StatusSiteOverloaded
	StatusSiteFrozen             = context.StatusSiteFrozen
	StatusNetworkReadTimeout     = context.StatusNetworkReadTimeout
)

HTTP status codes as registered with IANA. See: http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml. Raw Copy from the future(tip) net/http std package in order to reduce the import path of "net/http" for the users.

View Source
const (
	// B is the value of 1 byte.
	B = 1 << (10 * iota)
	// KB is the value of 1 kilobyte or 1024 bytes.
	KB
	// MB is the value of 1 megabyte or 1024 * 1024 bytes.
	MB
	// GB is the value of 1 gigabyte or 1024 * 1024 * 1024 bytes.
	GB
	// TB is the value of 1 terabyte or 1024 * 1024 * 1024 * 1024 bytes.
	TB
	// PB is the value of 1 petabyte or 1024 * 1024 * 1024 * 1024 * 1024 bytes.
	PB
	// EB is the value of 1 exabyte or 1024 * 1024 * 1024 * 1024 * 1024 * 1024 bytes.
	EB
)

Byte unit helpers.

View Source
const Version = "14.0.0"

Version is the current version of the Iris Web Framework.

Variables ΒΆ

View Source
var (
	// BuildRevision holds the vcs commit id information of the program's build.
	// To display the Iris' version please use the iris.Version constant instead.
	BuildRevision = buildinfo.BuildRevision
	// BuildTime holds the vcs commit time information of the program's build.
	BuildTime = buildinfo.BuildTime

	// RegisterOnInterrupt takes a function and appends it to the list of functions to be called on an interrupt signal (CTRL+C).
	RegisterOnInterrupt = signalhandler.Register
)
View Source
var (
	// QueryRequired is a shortcut for the `context.QueryRequired`:
	// an absent query value becomes a 400 Bad Request naming the key.
	QueryRequired = context.QueryRequired
	// QueryDefault is a shortcut for the `context.QueryDefault`:
	// the raw value to parse when the query key is absent.
	QueryDefault = context.QueryDefault
	// QueryZeroValues is a shortcut for the `context.QueryZeroValues`:
	// the raw values that mean "unset", e.g. "0" or "0000-00-00".
	QueryZeroValues = context.QueryZeroValues

	// AllowSort is a shortcut for the `context.AllowSort`:
	// a sort column outside the list becomes a 400 Bad Request.
	AllowSort = context.AllowSort
	// DenySort is a shortcut for the `context.DenySort`:
	// any sort request becomes a 400 Bad Request with the given message.
	DenySort = context.DenySort
	// ErrSortNotAllowed is a shortcut for the `context.ErrSortNotAllowed`:
	// the error ListFilter.SortColumn wraps for a column outside the
	// endpoint's allowed set.
	ErrSortNotAllowed = context.ErrSortNotAllowed
)
View Source
var (
	// Join is a shortcut for the `router.Join`.
	Join = router.Join
	// Prefix is a shortcut for the `router.Prefix`.
	Prefix = router.Prefix
	// Dependencies is a shortcut for the `router.Dependencies`.
	// Dependencies returns a Controller which can be used to register
	// dependencies to the controllers follows in the same `Router.Router` method call.
	// Useful when you have the same interface declared for different services
	// that can be binded to more than one controller.
	Dependencies = router.Dependencies
	// Middleware is a shortcut for the `router.Middleware`.
	// Middleware is a Controller which can be used
	// as a shortcut to add middlewares on Router.Router("/path", Middleware(handler), new(example.API)).
	Middleware = router.Middleware
)
View Source
var (
	// NewConditionalHandler returns a single Handler which can be registered
	// as a middleware.
	// Filter is just a type of Handler which returns a boolean.
	// Handlers here should act like middleware, they should contain `ctx.Next` to proceed
	// to the next handler of the chain. Those "handlers" are registered to the per-request context.
	//
	//
	// It checks the "filter" and if passed then
	// it, correctly, executes the "handlers".
	//
	// If passed, this function makes sure that the Context's information
	// about its per-request handler chain based on the new "handlers" is always updated.
	//
	// If not passed, then simply the Next handler(if any) is executed and "handlers" are ignored.
	// Example can be found at: _examples/06-middleware/conditional.
	//
	// A shortcut for the `context#NewConditionalHandler`.
	NewConditionalHandler = context.NewConditionalHandler

	// FromStd converts native http.Handler, http.HandlerFunc & func(w, r, next) to context.Handler.
	//
	// Supported form types:
	// 		 .FromStd(h http.Handler)
	// 		 .FromStd(func(w http.ResponseWriter, r *http.Request))
	// 		 .FromStd(func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc))
	//
	// A shortcut for the `context#FromStd`.
	// See `context#TryFromStd` for the non-panicking form.
	FromStd = context.FromStd

	// CookieOverride is a CookieOption which overrides the cookie explicitly to the given "cookie".
	//
	// A shortcut for the `context#CookieOverride`.
	CookieOverride = context.CookieOverride
	// CookieDomain is a CookieOption which sets the cookie's Domain field.
	// If empty then the current domain is used.
	//
	// A shortcut for the `context#CookieDomain`.
	CookieDomain = context.CookieDomain
	// CookieAllowReclaim accepts the Context itself.
	// If set it will add the cookie to (on `SetCookie`, `AddCookie`)
	// or remove the cookie from (on `RemoveCookie`) the Request object too.
	//
	// A shortcut for the `context#CookieAllowReclaim`.
	CookieAllowReclaim = context.CookieAllowReclaim
	// CookieAllowSubdomains set to the Cookie Options
	// in order to allow subdomains to have access to the cookies.
	// It sets the cookie's Domain field (if was empty) and
	// it also sets the cookie's SameSite to lax mode too.
	//
	// A shortcut for the `context#CookieAllowSubdomains`.
	CookieAllowSubdomains = context.CookieAllowSubdomains
	// CookieSameSite sets a same-site rule for cookies to set.
	// SameSite allows a server to define a cookie attribute making it impossible for
	// the browser to send this cookie along with cross-site requests. The main
	// goal is to mitigate the risk of cross-origin information leakage, and provide
	// some protection against cross-site request forgery attacks.
	//
	// See https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00 for details.
	//
	// A shortcut for the `context#CookieSameSite`.
	CookieSameSite = context.CookieSameSite
	// CookieSecure sets the cookie's Secure option on set operation if the current request's
	// connection is using TLS. See `CookieHTTPOnly` too.
	//
	// A shortcut for the `context#CookieSecure`.
	CookieSecure = context.CookieSecure
	// CookieSecureForce is a `CookieOption`. It sets the cookie's Secure option to true every time.
	//
	// A shortcut for the `context#CookieSecureForce`.
	CookieSecureForce = context.CookieSecureForce
	// CookieHTTPOnly is a `CookieOption`.
	// Use it to set the cookie's HttpOnly field to false or true.
	// HttpOnly field defaults to true for `RemoveCookie` and `AddCookie`.
	//
	// A shortcut for the `context#CookieHTTPOnly`.
	CookieHTTPOnly = context.CookieHTTPOnly
	// CookiePath is a `CookieOption`.
	// Use it to change the cookie's Path field.
	//
	// A shortcut for the `context#CookiePath`.
	CookiePath = context.CookiePath
	// CookieCleanPath is a `CookieOption`.
	// Use it to clear the cookie's Path field, exactly the same as `CookiePath("")`.
	//
	// A shortcut for the `context#CookieCleanPath`.
	CookieCleanPath = context.CookieCleanPath
	// CookieExpires is a `CookieOption`.
	// Use it to change the cookie's Expires and MaxAge fields by passing the lifetime of the cookie.
	//
	// A shortcut for the `context#CookieExpires`.
	CookieExpires = context.CookieExpires
	// CookiePartitioned is a `CookieOption`.
	// It enables the "Partitioned" cookie attribute, which binds a third-party
	// cookie to the top-level site that caused it to be set (CHIPS).
	//
	// A shortcut for the `context#CookiePartitioned`.
	CookiePartitioned = context.CookiePartitioned
	// CookieEncoding accepts a value which implements `Encode` and `Decode` methods.
	// It calls its `Encode` on `Context.SetCookie` and `AddCookie` methods.
	// And on `Context.Cookie` method it calls its `Decode`.
	//
	// A shortcut for the `context#CookieEncoding`.
	CookieEncoding = context.CookieEncoding

	// IsErrEmptyJSON reports whether the given "err" is caused by a
	// Context.ReadJSON call when the request body
	// didn't start with { or it was totally empty.
	IsErrEmptyJSON = context.IsErrEmptyJSON
	// IsErrPath can be used at `context#ReadForm` and `context#ReadQuery`.
	// It reports whether the incoming error is caused by an unknown field
	// (`schema.UnknownKeyError`), which can be ignored when server allows
	// unknown post values to be sent by the client.
	//
	// A shortcut for the `context#IsErrPath`.
	IsErrPath = context.IsErrPath
	// IsErrCanceled reports whether the "err" is caused by a cancellation or timeout.
	//
	// A shortcut for the `context#IsErrCanceled`.
	IsErrCanceled = context.IsErrCanceled
	// ErrEmptyForm is the type error which API users can make use of
	// to check if a form was empty on `Context.ReadForm`.
	//
	// A shortcut for the `context#ErrEmptyForm`.
	ErrEmptyForm = context.ErrEmptyForm
	// ErrEmptyFormField reports whether if form value is empty.
	// An alias of `context.ErrEmptyFormField`.
	ErrEmptyFormField = context.ErrEmptyFormField
	// ErrNotFound reports whether a key was not found, useful
	// on post data, versioning feature and others.
	// An alias of `context.ErrNotFound`.
	ErrNotFound = context.ErrNotFound
	// XMLMap wraps a map[string]any to compatible xml marshaler,
	// in order to be able to render maps as XML on the `Context.XML` method.
	//
	// Example: `Context.XML(XMLMap("Root", map[string]any{...})`.
	//
	// A shortcut for the `context#XMLMap`.
	XMLMap = context.XMLMap
	// ErrHijackNotSupported is returned by the Hijack method to
	// indicate that Hijack feature is not available.
	//
	// A shortcut for the `context#ErrHijackNotSupported`.
	ErrHijackNotSupported = context.ErrHijackNotSupported

	// PrivateError accepts an error and returns a wrapped private one.
	// A shortcut for the `context#PrivateError` function.
	PrivateError = context.PrivateError

	// TrimParamFilePart is a middleware which trims any last part after a dot (.) character
	// of the current route's dynamic path parameters.
	// A shortcut for the `context#TrimParamFilePart` function.
	TrimParamFilePart Handler = context.TrimParamFilePart
)
View Source
var (
	// Timeout returns a new Timeout configuration builder.
	//
	// It's a shortcut of the `server#Timeout`.
	Timeout = server.Timeout

	// StatusText returns a text for the HTTP status code. It returns the empty
	// string if the code is unknown.
	//
	// Shortcut for context#StatusText.
	StatusText = context.StatusText
)
View Source
var DefaultOptions = Options{
	LogLevel: "info",
	Router:   RouterOptions{},
	Context:  context.DefaultContextOptions(),
}

DefaultOptions returns the default configuration for an Iris Application.

Functions ΒΆ

func LoadConfiguration ΒΆ

func LoadConfiguration[T any](envKey, filename string) (T, error)

LoadConfiguration reads a YAML document into T from the environment variable named envKey when it is set, otherwise from filename. It is the whole-service counterpart of Options.Bind, which reads the framework options only.

The environment variable may hold either the YAML document itself or a path to it: a value that names an existing file is read as a file, anything else is decoded as the document. A container can therefore pass the configuration inline or mount it as a file without the program knowing which.

If T (or *T) implements interface{ BindEnv() } it runs after decoding, so environment overrides win over the document. Embed BaseConfiguration to get that behaviour for the fields every service shares.

It reads the same YAML decoder Options.Bind and YAML use. It is not a generic Options.Bind: that one is hardcoded to the SERVER_CONFIG variable and always reads its value as a document, never as a path.

Usage:

type Configuration struct {
	iris.BaseConfiguration `yaml:",inline"`

	DatabaseURL string `yaml:"DatabaseURL"`
}

c, err := iris.LoadConfiguration[Configuration]("MY_SERVICE_CONFIG", "configuration.yml")

func NewContextWrapper ΒΆ

func NewContextWrapper[T any, contextPtr context.ContextSetterPtr[T]]() *context.ContextWrapper[contextPtr]

NewContextWrapper returns a new ContextWrapper. It uses the default pool. The default pool's AcquireFunc returns a zero value of T. The default pool's ReleaseFunc does nothing.

Usage:

Initialize a new context wrapper using the default pool, where the myCustomContext SHOULD implement the `SetContext(ctx iris.Context)` method.

w := iris.NewContextWrapper[myCustomContext]()

Use it to wrap the handlers.

app.Get("/", w.Handler(index))

See the `context/NewContextWrapperWithPool` for more.

func PrintBuildInfo ΒΆ

func PrintBuildInfo(w io.Writer)

PrintBuildInfo prints the Iris web framework version and current program's build information.

Types ΒΆ

type APIBuilder ΒΆ

type APIBuilder interface {
	// API registers controllers for a specific route group, enabling modular
	// API organization with optional middleware per group.
	//
	// Controller types supported:
	//   - Structs implementing Routing(iris.Router) method
	//   - Factory functions that return controllers (with dependency injection)
	//   - Direct iris.Handler functions
	//   - Middleware functions (using iris.Middleware wrapper)
	//
	// Route group features:
	//   - Each API call creates a new route group under the specified path
	//   - Groups can have their own middleware stack
	//   - Controllers can access injected dependencies
	//   - Automatic method routing based on HTTP verbs (GET, POST, etc.)
	//
	// Parameters:
	//   - prefixPath: Route group prefix (e.g., "/users", "/admin", "/v1/products")
	//   - controllers: Controllers and/or middleware for this group
	//
	// Examples:
	//   // Simple controller registration
	//   API("/users", NewUserController)
	//
	//   // Controller with middleware
	//   API("/admin",
	//       basicauth.Default(map[string]string{"admin": "secret"}),
	//       NewAdminController)
	//
	//   // Multiple controllers in one group
	//   API("/api",
	//       NewUserController,
	//       NewProductController,
	//       NewOrderController)
	//
	//   // Factory function with dependency injection
	//   API("/posts", func(db *sql.DB, cache *redis.Client) *PostController {
	//       return &PostController{db: db, cache: cache}
	//   })
	//
	// Controller example:
	//   type UserController struct {
	//       userService *UserService
	//   }
	//
	//   func NewUserController(service *UserService) *UserController {
	//       return &UserController{userService: service}
	//   }
	//
	//   func (c *UserController) Routing(r iris.Router) {
	//       r.Get("/", c.listUsers)      // GET /users/
	//       r.Post("/", c.createUser)    // POST /users/
	//       r.Get("/{id}", c.getUser)    // GET /users/{id}
	//       r.Put("/{id}", c.updateUser) // PUT /users/{id}
	//       r.Delete("/{id}", c.deleteUser) // DELETE /users/{id}
	//   }
	//
	// Returns APIBuilder for registering additional API groups.
	API(prefixPath string, controllers ...any) APIBuilder

	// Build compiles and finalizes the application configuration, creating
	// the complete Iris application instance ready for deployment.
	//
	// Build process:
	//   1. Validates all registered dependencies
	//   2. Initializes the dependency injection container
	//   3. Applies all registered middleware in correct order
	//   4. Registers all API routes and controllers
	//   5. Sets up error handlers and recovery middleware
	//   6. Validates route patterns and conflicts
	//
	// When to call Build():
	//   - Always: it is the terminal builder step, Listen and Run are methods
	//     of the *Application it returns
	//   - Useful for testing (build without starting the server)
	//   - Required for custom server configurations
	//
	// Returns:
	//   - *Application: The fully configured Iris application instance
	//
	// The returned Application is already built. Its mux was compiled from
	// the routes registered up to this point, and a route registered on it
	// afterwards is never served (the router logs a warning naming it and
	// the file it came from). Register those through API instead, before
	// Build.
	//
	// The returned Application can be used for:
	//   - Custom middleware registration on the pre-routing chain
	//   - Testing with httptest
	//   - Custom server startup with specific options
	//
	// Examples:
	//   // Simple usage
	//   app := builder.Build()
	//   app.Listen(":8080")
	//
	//   // Custom server configuration
	//   app := builder.Build()
	//   app.Run(iris.ServerOptions{Addr: ":443", CertFile: "cert.pem", KeyFile: "key.pem"})
	//
	//   // Testing
	//   app := builder.Build()
	//   e := httptest.New(t, app)
	//   e.GET("/api/users").Expect().Status(httptest.StatusOK)
	//
	// Note: Build() panics if there are configuration errors. This is
	// intentional to catch issues early during application startup.
	Build() *Application
}

APIBuilder is the final step for registering API controllers and building the complete application with all configured middleware and services.

type Application ΒΆ

type Application struct {
	// routing embedded | exposing RouterBuilder's and Router's public API.
	*router.RouterBuilder

	// OnBuild is a single function which
	// is fired on the first `Build` method call.
	// If reports an error then the execution
	// is stopped and the error is logged.
	// It's nil by default except when `Switch` instead of `New` or `Default`
	// is used to initialize the Application.
	// Users can wrap it to accept more events.
	OnBuild func() error

	// OnBuilt is a single function which is fired after the application is built.
	OnBuilt func() error
	// contains filtered or unexported fields
}

Application is responsible to manage the state of the application. It contains and handles all the necessary parts to create a fast web server.

func Default ΒΆ

func Default() *Application

Default returns a new Application with a development-friendly setup already in place. Routes are registered on it exactly as on New: the returned application is NOT built yet, so anything registered after this call is served.

It registers, in execution order:

  • the "debug" logger level,
  • the rest/errors path parameter type and context error handlers,

and, as pre-routing middleware in this order:

  • panic recovery, which reports the panic through rest/errors,
  • CORS for every origin ("*"),
  • the "Server: Iris" response header,
  • request and response compression, bounded by compress.Safe,
  • rest/errors.Handler, which renders a failure status nobody gave a body to,
  • a request id per request (the requestid middleware).

So a bare failure status (ctx.StopWithStatus(403), ctx.NotFound()) and an unknown path answer the rest/errors JSON envelope, as they do on a NewBuilder application. Register your own with HandleNoRoute or HandleNoMethod before the application is built to answer 404 or 405 yourself.

Use it while you explore, not in production: see NewBuilder for an application whose CORS, logging, health and error handling you choose.

Usage:

app := iris.Default()
app.Get("/", func(ctx iris.Context) {...})
app.Listen(":8080")
Example ΒΆ

Default pre-registers a debug logger, permissive CORS, panic recovery and request IDs. Reach for it while exploring; configure the middleware yourself before you ship.

The application it returns is not built yet, so routes are registered on it exactly as on New.

package main

import (
	"fmt"
	"net/http/httptest"

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

func main() {
	app := iris.Default()

	app.Get("/", func(ctx iris.Context) {
		ctx.JSON(iris.Map{"message": "Hello, World!"})
	})

	// In a program this is app.Listen(":8080"), which builds and serves.
	if err := app.Build(); err != nil {
		panic(err)
	}

	w := httptest.NewRecorder()
	app.Handler.ServeHTTP(w, httptest.NewRequest("GET", "/", nil))

	fmt.Println(w.Code)
	fmt.Println(w.Body.String())
}
Output:
200
{"message":"Hello, World!"}

func New ΒΆ

func New(configurators ...Configurator) *Application

New creates and returns a fresh empty iris *Application instance.

Usage:

app := iris.New(iris.Options{...})
app.Get("/", func(ctx iris.Context) {...})
app.Listen(":8080")
Example ΒΆ

A path parameter carries a type. A request whose value does not match is answered before the handler runs, so the handler never sees a bad id.

package main

import (
	"fmt"
	"net/http/httptest"

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

func main() {
	app := iris.New()

	app.Get("/products/{id:uuid}", func(ctx iris.Context) {
		ctx.JSON(iris.Map{"id": ctx.Params().GetString("id")})
	})

	if err := app.Build(); err != nil {
		panic(err)
	}

	// The rejection status depends on how errors are configured, so this only
	// reports whether the request reached the handler at all.
	for _, path := range []string{
		"/products/6ba7b810-9dad-11d1-80b4-00c04fd430c8",
		"/products/not-a-uuid",
	} {
		w := httptest.NewRecorder()
		app.Handler.ServeHTTP(w, httptest.NewRequest("GET", path, nil))
		fmt.Println(w.Code == 200)
	}
}
Output:
true
false

func (*Application) AddCloser ΒΆ

func (app *Application) AddCloser(fn any)

AddCloser adds a function, or a structure which completes the io.Closer, which will be executed when the server is closed.

func (*Application) Build ΒΆ

func (app *Application) Build() error

Build prepares the Iris Application to run by constructing its internal state. This method is called automatically when the application's Run method is invoked, but it can also be called manually if needed.

The Build process includes the following steps:

  1. If the application has already been built, it returns immediately.

  2. If an OnBuild callback is set, it is executed. If the callback returns an error, the build process is halted and the error is returned.

  3. The application's logger level is set based on the configuration options.

  4. If the application is not in a downgraded state, the router is built through BuildRouter with the application's Router options, logger and context pool. Lowercase routing is enforced there when Options.Router.ForceLowercaseRouting is set.

  5. If an OnBuilt callback is set, it is executed. If the callback returns an error, the build process is halted and the error is returned.

The method returns an error if any step of the build process fails. After the method had invoked, the Application's Handler field is a compatible http.Handler that can be served by any standard http server.

Build runs once. A second call returns nil without rebuilding, so routes registered after the first call are not served. This matters when the Application came from NewBuilder, whose own Build already ran this one: register those routes through the builder's API step instead.

Usage:

app := iris.New()
err := app.Build()
if err != nil {
    log.Fatal(err)
}

w := httptest.NewRecorder()
app.Handler.ServeHTTP(w, req)

func (*Application) BuildRouter ΒΆ

func (app *Application) BuildRouter() error

BuildRouter builds the router, it's being called automatically by the `Run` & `Listen` methods.

func (*Application) Configure ΒΆ

func (app *Application) Configure(configurators ...Configurator) *Application

Configure can called when modifications to the framework instance needed. It accepts the framework instance and returns an error which if it's not nil it's printed to the logger. See Options and Configurator for what a configurator can change.

Returns itself in order to be used like `app:= New().Configure(...)`

func (*Application) ContextPool ΒΆ

func (app *Application) ContextPool() *context.Pool

ContextPool returns the Iris sync.Pool which holds the contexts values. Iris automatically releases the request context, so you don't have to use it. It's only useful to manually release the context on cases that connection is hijacked by a third-party middleware and the http handler return too fast.

func (*Application) EditOptions ΒΆ

func (app *Application) EditOptions(fn func(*Options))

EditOptions allows the caller to change the application's options. Should be called before BuildRouter, Build, Listen or Run methods.

The changes reach the root Router and every Router created afterwards. A child Router (Router, Subdomain) copies the context options when it is created and keeps that copy, so call EditOptions before registering any child Router if the change is an Options.Context one.

func (*Application) IsDebug ΒΆ

func (app *Application) IsDebug() bool

IsDebug reports whether the application is running under debug/development mode. It's just a shortcut of Logger().Level >= golog.DebugLevel. The same method exists as Context.IsDebug() too.

func (*Application) Listen ΒΆ

func (app *Application) Listen(addrHostPort string) error

Listen builds the application's components and starts the server on the specified TCP network address. The address must be in the form "host:port", where the host must be either a literal IP address or a hostname that can be resolved to IP addresses. The port must be a literal port number or a service name. If the host is a literal IPv6 address, it must be enclosed in square brackets, such as "[2001:db8::1]:80".

If the Addr parameter is an empty string, the method defaults to ":http".

The method sets various server options, including network type, keep-alive duration, socket sharding, and log writer before calling the Run method to start the server.

Listen blocks until the server stops. A graceful shutdown (an interrupt signal, or Application.Shutdown) returns nil. A failed start (a build error, or a listener that could not be opened) is logged and the process exits with status 1, so a program with nothing else to do calls Listen as a statement. Set Options.DisableFatalRun to have the error returned instead, for a process that runs more than one server or a test that opens a real listener.

Usage:

app := iris.New()
app.Listen(":8080")

func (*Application) Logger ΒΆ

func (app *Application) Logger() *golog.Logger

Logger returns the golog logger instance(pointer) that is being used inside the "app".

Available levels: - "disable" - "fatal" - "error" - "warn" - "info" - "debug" Usage: app.Logger().SetLevel("error") Or set it through Options.LogLevel, either at construction or later with app.EditOptions. Defaults to "info" level.

Callers can use the application's logger which is the same `golog.Default.LastChild()` logger, to print custom logs too. Usage: app.Logger().Error/Errorf("...") app.Logger().Warn/Warnf("...") app.Logger().Info/Infof("...") app.Logger().Debug/Debugf("...")

Setting one or more outputs: app.Logger().SetOutput(io.Writer...) Adding one or more outputs : app.Logger().AddOutput(io.Writer...)

Adding custom levels requires import of the `github.com/kataras/golog` package:

First we create our level to a golog.Level
in order to be used in the Log functions.
var SuccessLevel golog.Level = 6
Register our level, just three fields.
golog.Levels[SuccessLevel] = &golog.LevelMetadata{
	Name:    "success",
	RawText: "[SUCC]",
	// ColorfulText (Green Color[SUCC])
	ColorfulText: "\x1b[32m[SUCC]\x1b[0m",
}

Usage: app.Logger().SetLevel("success") app.Logger().Logf(SuccessLevel, "a custom leveled log message")

func (*Application) RegisterOnBuild ΒΆ

func (app *Application) RegisterOnBuild(beforeBuild, afterBuild func() error)

RegisterOnBuild registers callback functions to be executed before and after the application is built. The beforeBuild callback runs at the very start of `Build`, before the logger level is set and before the router is built; afterBuild runs once the internal state is constructed. Both run before the server is started and an error returned by either one aborts the build.

func (*Application) Run ΒΆ

func (app *Application) Run(options ServerOptions) error

Run starts the Iris Application with the provided server options. It performs several key steps to ensure the application is correctly set up before starting the server:

  1. Builds the application's router and other necessary components.

  2. Ensures that a log writer is set for the server. If not provided in the options, it defaults to the application's logger output.

3. Prints the build information unless startup logs are explicitly disabled.

4. Resolves and sets the host for the application using the provided address if the host is not already set.

5. Configures the allowed hosts for the server, including subdomains, based on the application's routes.

  1. Initializes a new server with the given options and sets up a listener to update the application's host based on the final listener's URL.

7. Prepends the server's shutdown function to the application's list of closers for proper cleanup on termination.

8. Starts the HTTP(S) server and blocks until it stops.

Run blocks until the server stops. A graceful shutdown returns nil. A failed start, or a server that stops with an error, is logged and the process exits with status 1; with Options.DisableFatalRun the error is logged at error level and returned to the caller instead. See Application.Listen.

Usage:

app := iris.New()
app.Run(iris.ServerOptions{Addr: ":8080"})

func (*Application) Shutdown ΒΆ

func (app *Application) Shutdown(ctx stdContext.Context) error

Shutdown gracefully terminates the application by running every registered closer, in order, passing the given context to each one. The running server's own Shutdown is one of those closers: `Run` prepends it to the list, so it is the first to be called.

The method takes a context (ctx) which allows for timeout and cancellation capabilities. This is particularly useful when you want to control how long the shutdown process should wait before forcefully closing.

Errors from individual closers are accumulated with errors.Join, so each one can be matched through errors.Is or errors.As. It returns nil when every closer succeeds. Calling it before `Run` simply closes whatever else was registered through `AddCloser`.

Usage:

app := iris.New()
[...]
app.Shutdown(context.Background())

func (*Application) String ΒΆ

func (app *Application) String() string

String completes the fmt.Stringer interface. It returns the given application's name.

type BaseConfiguration ΒΆ

type BaseConfiguration struct {
	// Host is the network interface the server listens on. Empty means every
	// interface. See Addr.
	//
	// It is not Iris.Host: that one is the trusted domain the router matches
	// subdomains against, and Addr never reads it.
	Host string `yaml:"Host" json:"host"`
	// Port is the TCP port the server listens on. Zero means 8080. See Addr.
	Port int `yaml:"Port" json:"port"`
	// AllowOrigin is the origin line for the CORS middleware,
	// as Builder.AllowOrigin accepts it ("*", "none" or a comma-separated list).
	AllowOrigin string `yaml:"AllowOrigin" json:"allow_origin"`
	// EnableCompression reports whether request and response compression is on,
	// as Builder.Compression accepts it.
	EnableCompression bool `yaml:"EnableCompression" json:"enable_compression"`
	// RequestLog reports whether the access log is on,
	// as Builder.LogRequests accepts it.
	RequestLog bool `yaml:"RequestLog" json:"request_log"`
	// Iris is the framework configuration, as iris.New accepts it.
	Iris Options `yaml:"Iris" json:"iris"`
}

BaseConfiguration is the part every service's configuration has in common: where the server listens, which origin it answers and how the framework itself is configured. Embed it, inline, and add the service's own fields:

type Configuration struct {
	iris.BaseConfiguration `yaml:",inline"`

	DatabaseURL string `yaml:"DatabaseURL"`
}

Load it with LoadConfiguration, which runs BindEnv for you, and listen with app.Listen(c.Addr()).

func (*BaseConfiguration) Addr ΒΆ

func (c *BaseConfiguration) Addr() string

Addr returns the "host:port" address for Application.Listen. An empty Host listens on every interface (":port") and a zero Port defaults to 8080.

func (*BaseConfiguration) BindEnv ΒΆ

func (c *BaseConfiguration) BindEnv()

BindEnv overrides the decoded Host, Port and AllowOrigin from the environment, so the same document can be deployed unchanged everywhere. The variables are HOST, PORT, HTTP_PLATFORM_PORT and ALLOW_ORIGIN.

HTTP_PLATFORM_PORT wins over PORT: a hosting platform that picks the port for the process (IIS and Azure App Service do) passes it there, while PORT may still carry the value baked into the image.

LoadConfiguration calls this after decoding. Call it yourself only when the configuration was built by other means.

type Builder ΒΆ

type Builder interface {
	// Prefix sets the API Router prefix path for all registered routes.
	// This is useful for versioning (e.g., "/api/v1") or organizing APIs.
	//
	// Parameters:
	//   - prefixPath: The path prefix (must start with "/")
	//
	// Example:
	//   Prefix("/api/v1")  // All routes will be under /api/v1/*
	//
	// Returns CorsBuilder for the next configuration step.
	Prefix(prefixPath string) CorsBuilder

	// NoPrefix disables the API Router prefix path, making routes available
	// directly under the root path. This is equivalent to Prefix("").
	//
	// Example:
	//   NoPrefix()  // Routes available directly under /*
	//
	// Returns CorsBuilder for the next configuration step.
	NoPrefix() CorsBuilder
}

Builder is the simplified API builder that provides a step-by-step approach to building production-ready Iris applications with common middleware, security features, and best practices built-in.

The Builder enforces a logical order of configuration steps to ensure middleware and features are applied in the correct sequence.

func NewBuilder ΒΆ

func NewBuilder(configurators ...Configurator) Builder

NewBuilder returns a step-by-step builder for a production-ready Iris application: the common middleware, the error handling and the dependency container are set up in the right order for you.

The order is enforced by the compiler, not by documentation. Each step returns a narrower interface that exposes only the steps that may follow:

  1. Prefix(path) or NoPrefix(): where the API routes live
  2. AllowOrigin(line) or Cors(*cors.CORS): CORS
  3. Compression(bool): request and response compression
  4. LogRequests(bool) or LogRequestsWith(*accesslog.AccessLog): the access log
  5. Health(bool, env, developer) or NoHealth(): the /health probe
  6. Errors(*errors.Options), Deferrables(...), Services(...)
  7. RouterMiddlewares(...), then Middlewares(...)
  8. API(path, controllers...), repeatable
  9. Build() *Application

Steps 1 to 6 only record what they are given. The middleware is registered on the first RouterMiddlewares or Middlewares call, guarded by a sync.Once, which is why the order it runs in is fixed no matter how the chain is written; see RouterMiddlewares for that order.

A failure status that reaches the client with nothing written answers with the rest/errors JSON envelope, next to the errors the application reports through rest/errors itself. That covers:

  • a status of 400 or above set by a route handler or by a middleware given to RouterMiddlewares, Middlewares or API, whether or not it stopped the chain: ctx.StopWithStatus(403), ctx.NotFound(), the 401 of the jwt and basicauth middleware, a file the file server does not have;
  • an unknown path (404);
  • a method a known path does not serve (405, when Options.Router.FireMethodNotAllowed is on; it is off by default, and the answer is then the 404 one).

Two failures are answered ahead of that handler and keep their bare status:

  • a rejection from a handler a Configurator registered with UseRouter. It runs before the builder's own middleware, this one included;
  • the 415 of the compression middleware, for a request body that is not what its Content-Encoding says.

What the client reads for an error stored on the Context (ctx.StopWithError, ctx.StopWithPlainError, ctx.SetErr): nothing of a private error (iris.PrivateError), and no mapping is asked about one. It renders the status text below 500 ("Unauthorized") and, at 500 and above, the generic "server error" while the error is logged. An error a mapping recognises, and that is not private, renders through its mapping. Any other error: below 500 its text is the message; at 500 and above the text is logged and the client reads the generic "server error", except for a stored *errors.Error that is not private, which is sent as it is.

A response that has a body, that declares a Content-Length, or whose status line is already on the wire, is left as it is, and so is a hijacked connection. To answer 404 or 405 yourself, register HandleNoRoute or HandleNoMethod from a Configurator given here: the builder fills those two slots only when they are empty at Build.

Parameters:

  • configurators: Optional Iris application configurators for advanced setup

For a worked example see the package examples for this function.

Example ΒΆ

The builder returns a narrower interface at every step, so a chain written in the wrong order does not compile. Health comes before Services, Services before Middlewares, and API last.

Build closes the chain. Routes registered on the returned Application after that point are not picked up, so register them through API.

package main

import (
	"fmt"
	"net/http/httptest"

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

// greetAPI is a controller: the builder resolves its constructor through the
// dependency container and calls Routing to register the group's routes.
type greetAPI struct{}

func newGreetAPI() *greetAPI { return &greetAPI{} }

func (api *greetAPI) Routing(r iris.Router) {
	r.Get("/{name:string}", func(ctx iris.Context) {
		ctx.WriteString("Hello, " + ctx.Params().GetString("name"))
	})
}

func main() {
	app := iris.NewBuilder().
		NoPrefix().
		AllowOrigin("*").
		Compression(true).
		LogRequests(false).
		NoHealth().
		Services().
		RouterMiddlewares().
		Middlewares().
		API("/greet", newGreetAPI).
		Build()

	w := httptest.NewRecorder()
	app.Handler.ServeHTTP(w, httptest.NewRequest("GET", "/greet/gopher", nil))

	fmt.Println(w.Body.String())
}
Output:
Hello, gopher
Example (Full) ΒΆ

A full chain: the container resolves openExampleDB into the repository, the repository into the service and the service into the controller, and the database's Close is registered as a shutdown closer because Services recognises a value with a Close() error method.

package main

import (
	"context"
	"database/sql"
	"fmt"
	"net/http/httptest"

	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/rest/errors"
)

// The pieces a real API is wired from: a resource with a Close, a repository
// over it, a service over that, and a controller that the container builds
// from the service.
type exampleDB struct{ closed bool }

func openExampleDB() *exampleDB { return &exampleDB{} }

func (db *exampleDB) Close() error {
	db.closed = true
	return nil
}

type noteRepository struct{ db *exampleDB }

func newNoteRepository(db *exampleDB) *noteRepository {
	return &noteRepository{db: db}
}

func (r *noteRepository) list() []string { return []string{"first", "second"} }

type noteService struct{ repo *noteRepository }

func newNoteService(repo *noteRepository) *noteService {
	return &noteService{repo: repo}
}

func (s *noteService) list() []string { return s.repo.list() }

type noteAPI struct{ service *noteService }

func newNoteAPI(service *noteService) *noteAPI {
	return &noteAPI{service: service}
}

func (api *noteAPI) Routing(r iris.Router) {
	r.Get("/", func(ctx iris.Context) {
		ctx.JSON(api.service.list())
	})
}

func main() {
	app := iris.NewBuilder().
		Prefix("/api").
		AllowOrigin("https://example.com").
		Compression(true).
		LogRequests(false).
		Health(true, "development", "you@example.com").
		Errors(errors.NewOptions().
			MapErrors(errors.NotFound, sql.ErrNoRows)).
		Deferrables(func() { /* stop background workers */ }).
		Services(
			openExampleDB(),
			newNoteRepository,
			newNoteService,
		).
		RouterMiddlewares(func(ctx iris.Context) {
			ctx.SetHeader("X-Api", "notes")
			ctx.Next()
		}).
		Middlewares(func(service *noteService) iris.Handler {
			return func(ctx iris.Context) {
				ctx.Values().Set("notes", len(service.list()))
				ctx.Next()
			}
		}).
		API("/notes", newNoteAPI).
		Build()

	w := httptest.NewRecorder()
	app.Handler.ServeHTTP(w, httptest.NewRequest("GET", "/api/notes", nil))

	fmt.Println(w.Header().Get("X-Api"))
	fmt.Println(w.Body.String())

	if err := app.Shutdown(context.Background()); err != nil {
		panic(err)
	}
}
Output:
notes
["first","second"]

type CompressionBuilder ΒΆ

type CompressionBuilder interface {
	// Compression enables or disables automatic response compression using
	// gzip or other client-preferred algorithms (brotli, deflate).
	//
	// The compression middleware automatically:
	//   - Detects client compression support via Accept-Encoding header
	//   - Compresses responses above a minimum size threshold
	//   - Skips compression for already-compressed content types
	//   - Handles streaming responses efficiently
	//
	// Performance Notes:
	//   - Enable for production APIs to reduce bandwidth by 60-80%
	//   - Minimal CPU overhead for most applications
	//   - Particularly effective for JSON responses
	//
	// Parameters:
	//   - enableReadWriteCompression: true to enable, false to disable
	//
	// Example:
	//   Compression(true)   // Enable compression (recommended for production)
	//   Compression(false)  // Disable compression (useful for debugging)
	//
	// Returns RequestLoggingBuilder for the next configuration step.
	Compression(enableReadWriteCompression bool) RequestLoggingBuilder
}

CompressionBuilder configures HTTP response compression to reduce bandwidth usage and improve response times, especially for JSON APIs and large payloads.

type Configurator ΒΆ

type Configurator interface {
	Configure(*Application)
}

Configurator is just an interface which contains a method that accepts the framework instance. It's being used to configure the framework before the server starts.

type ConfiguratorFunc ΒΆ

type ConfiguratorFunc func(*Application)

ConfiguratorFunc is just a type of function which accepts the framework instance. It implements the Configurator interface.

func Defaults ΒΆ

func Defaults(edits ...func(*Options)) ConfiguratorFunc

Defaults returns a ConfiguratorFunc which sets the default options for the Iris Application. The edits are optional and are applied to the default options.

Usage:

app := iris.New(iris.Defaults(func(opts *iris.Options) {
	opts.LogLevel = "debug"
	opts.Context.RemoteAddrHeaders = []string{"X-Forwarded-For"}
}))

func (ConfiguratorFunc) Configure ΒΆ

func (c ConfiguratorFunc) Configure(app *Application)

Configure implements the Configurator interface.

type Context ΒΆ

type Context = *context.Context

Context is the middle-man server's "object" for the clients.

A New context is being acquired from a sync.Pool on each connection. The Context is the most important thing on the iris's http flow.

Developers send responses to the client's request through a Context. Developers get request information from the client's request by a Context.

type ContextOptions ΒΆ

type ContextOptions = context.ContextOptions

ContextOptions is a type alias for the `context.ContextOptions`. It carries the per-request settings, among them PostMaxMemory, BodyMaxMemory, RemoteAddrHeaders, RequestValidator and ErrorHandler. Reachable as Options.Context.

type ContextPatches ΒΆ

type ContextPatches struct {
	// contains filtered or unexported fields
}

ContextPatches contains the available global Iris context modifications.

func (*ContextPatches) GetDomain ΒΆ

func (cp *ContextPatches) GetDomain(patchFunc func(hostport string) string)

GetDomain modifies the way a domain is fetched from `Context#Domain` method, which is used on subdomain redirect feature, i18n's language cookie for subdomain sharing and the rewrite middleware.

func (*ContextPatches) ResolveFS ΒΆ

func (cp *ContextPatches) ResolveFS(patchFunc func(fsOrDir any) fs.FS)

ResolveFS modifies the default way to resolve a filesystem by any type of value. It affects the view engine's filesystem resolver.

func (*ContextPatches) ResolveHTTPFS ΒΆ

func (cp *ContextPatches) ResolveHTTPFS(patchFunc func(fsOrDir any) http.FileSystem)

ResolveHTTPFS modifies the default way to resolve a filesystem by any type of value. It affects the Application's API Builder's `fileserver.Handler` method.

func (*ContextPatches) SetDefaultCookieExpiration ΒΆ

func (cp *ContextPatches) SetDefaultCookieExpiration(patch time.Duration)

SetDefaultCookieExpiration modifies the lifetime Context.AddCookie gives a cookie when no CookieExpires option is passed (context.DefaultCookieExpiration, 365 days by default).

func (*ContextPatches) SetDefaultPageSize ΒΆ

func (cp *ContextPatches) SetDefaultPageSize(size int)

SetDefaultPageSize modifies the page size PageOptions.GetLimit returns when the request asks for none (pagination.DefaultPageSize, 100 by default).

func (*ContextPatches) SetMaxPageSize ΒΆ

func (cp *ContextPatches) SetMaxPageSize(size int)

SetMaxPageSize modifies the largest page size PageOptions.GetLimit returns (pagination.MaxPageSize, 100000 by default). Zero or less means no bound.

func (*ContextPatches) Writers ΒΆ

func (cp *ContextPatches) Writers() *ContextWriterPatches

Writers returns the available global Iris context modifications for REST writers.

type ContextWriterPatches ΒΆ

type ContextWriterPatches struct{}

ContextWriterPatches features the context's writers patches.

func (*ContextWriterPatches) JSON ΒΆ

func (cwp *ContextWriterPatches) JSON(patchFunc func(ctx Context, v any, options *JSON) error)

JSON sets a custom function which runs and overrides the default behavior of the `Context#JSON` method.

func (*ContextWriterPatches) JSONP ΒΆ

func (cwp *ContextWriterPatches) JSONP(patchFunc func(ctx Context, v any, options *JSONP) error)

JSONP sets a custom function which runs and overrides the default behavior of the `Context#JSONP` method.

func (*ContextWriterPatches) Markdown ΒΆ

func (cwp *ContextWriterPatches) Markdown(patchFunc func(ctx Context, v []byte, options *Markdown) error)

Markdown sets a custom function which runs and overrides the default behavior of the `Context#Markdown` method.

func (*ContextWriterPatches) XML ΒΆ

func (cwp *ContextWriterPatches) XML(patchFunc func(ctx Context, v any, options *XML) error)

XML sets a custom function which runs and overrides the default behavior of the `Context#XML` method.

func (*ContextWriterPatches) YAML ΒΆ

func (cwp *ContextWriterPatches) YAML(patchFunc func(ctx Context, v any, indentSpace int) error)

YAML sets a custom function which runs and overrides the default behavior of the `Context#YAML` method.

type Controller ΒΆ

type Controller = router.Controller

Controller is a type alias for the `core/router#Controller`.

func ResolveController ΒΆ

func ResolveController[T any]() Controller

ResolveController is a shortcut for the `router.ResolveController`.

type Cookie = http.Cookie

Cookie is a type alias for the standard net/http Cookie struct type. See `Context.SetCookie`.

type CookieOption ΒΆ

type CookieOption = context.CookieOption

CookieOption is the type of function that is accepted on context's methods like `AddCookie`, `RemoveCookie` and `SetCookie` as their (last) variadic input argument to amend the end cookie's form.

Any custom or builtin `CookieOption` is valid, see `CookiePath`, `CookieCleanPath`, `CookieExpires` and `CookieHTTPOnly` for more.

An alias for the `context.CookieOption`.

type CorsBuilder ΒΆ

type CorsBuilder interface {
	// AllowOrigin configures CORS allowed origins for cross-domain requests.
	// This is a security-critical setting that controls which domains
	// can access your API from browsers.
	//
	// Parameters:
	//   - originLine: Allowed origins, comma-separated or "*" for all origins
	//
	// Security Notes:
	//   - Use "*" only for public APIs without sensitive data
	//   - For production, specify exact domains: "https://yourdomain.com"
	//   - Multiple origins: "https://app.com,https://admin.app.com"
	//   - Use "none" to disable CORS middleware entirely
	//
	// Examples:
	//   AllowOrigin("*")                                    // Allow all (use cautiously)
	//   AllowOrigin("https://myapp.com")                    // Single domain
	//   AllowOrigin("https://app.com,https://admin.com")    // Multiple domains
	//   AllowOrigin("none")                                 // Disable CORS
	//
	// Returns CompressionBuilder for the next configuration step.
	AllowOrigin(originLine string) CompressionBuilder

	// Cors registers a fully configured CORS value, for the settings
	// AllowOrigin does not reach: credentials, exposed headers, max age,
	// the origin extractor and the error handler.
	//
	// AllowOrigin(line) is the shorthand for:
	//
	//	Cors(cors.New().HandleErrorFunc(errors.FailedPrecondition.Err).AllowOrigin(line))
	//
	// The value is used as given, so call HandleErrorFunc yourself to keep
	// the error mapping AllowOrigin installs.
	//
	// A wildcard origin does not advertise credentials unless they are
	// enabled explicitly, because browsers reject the "*" plus credentials
	// combination. Call AllowCredentials when a non-browser client needs it:
	//
	//	Cors(cors.New().
	//		HandleErrorFunc(errors.FailedPrecondition.Err).
	//		AllowOrigin("*").
	//		AllowCredentials())
	//
	// Returns CompressionBuilder for the next configuration step.
	Cors(c *cors.CORS) CompressionBuilder
}

CorsBuilder configures Cross-Origin Resource Sharing (CORS) middleware. CORS is essential for web applications that need to handle requests from different domains, such as frontend applications.

type CountResponse ΒΆ

type CountResponse[N CountType] = context.CountResponse[N]

CountResponse is an alias for the `context.CountResponse[N]`: the {"count": N} body of Context.Count.

type CountType ΒΆ

type CountType = context.CountType

CountType is an alias for the `context.CountType`: the numeric constraint of Context.Count and Context.Paginated totals.

type DecodeFunc ΒΆ

type DecodeFunc = context.DecodeFunc

DecodeFunc is a generic type of decoder function. When the returned error is not nil the decode operation is terminated and the error is received by the ReadJSONStream method, otherwise it continues to read the next available object. Look the `Context.ReadJSONStream` method.

type ErrPrivate ΒΆ

type ErrPrivate = context.ErrPrivate

ErrPrivate if provided then the error saved in context should NOT be visible to the client no matter what. An alias for the `context.ErrPrivate`.

type Filter ΒΆ

type Filter = context.Filter

Filter is just a type of func(Context) bool which reports whether an action must be performed based on the incoming request.

See `NewConditionalHandler` for more. An alias for the `context/Filter`.

type GlobalPatches ΒΆ

type GlobalPatches struct {
	// contains filtered or unexported fields
}

GlobalPatches is a singleton that provides a uniform way to apply global/package-level modifications.

See the `Patches` package-level function.

func Patches ΒΆ

func Patches() *GlobalPatches

Patches returns the singleton of GlobalPatches, an easy way to modify global(package-level) configuration for Iris applications.

See its `Context` method.

Example: https://github.com/kataras/iris/blob/main/_examples/16-advanced/patches/main.go

func (*GlobalPatches) Context ΒΆ

func (p *GlobalPatches) Context() *ContextPatches

Context returns the available context patches.

type Handler ΒΆ

type Handler = context.Handler

A Handler responds to an HTTP request. It writes reply headers and data to the Context.ResponseWriter() and then return. Returning signals that the request is finished; it is not valid to use the Context after or concurrently with the completion of the Handler call.

Depending on the HTTP client software, HTTP protocol version, and any intermediaries between the client and the iris server, it may not be possible to read from the Context.Request().Body after writing to the context.ResponseWriter(). Cautious handlers should read the Context.Request().Body first, and then reply.

Except for reading the body, handlers should not modify the provided Context.

If Handler panics, the server (the caller of Handler) assumes that the effect of the panic was isolated to the active request. It recovers the panic, logs a stack trace to the server error log, and hangs up the connection.

func Component ΒΆ

func Component(component context.Component) Handler

Component returns a new Handler which can be registered as a main handler for a route. It's a shortcut handler that renders the given component as HTML through Context.RenderComponent.

func WithErrorHandler ΒΆ

func WithErrorHandler(handler context.ErrorHandler) Handler

WithErrorHandler returns a middleware which sets a custom error handler for the requests it runs on. It overrides the Options.Context.ErrorHandler value for those requests only, and applies on Render, RenderComponent, JSON, JSONP, XML, Markdown, YAML, Protobuf and MsgPack write errors.

Register it like any other middleware, on the application, a router or a single route:

app.Use(iris.WithErrorHandler(func(ctx iris.Context, err error) {
	ctx.StopWithPlainError(iris.StatusInternalServerError, err)
}))

To customize panic recovery errors instead, see middleware/recovery.WithErrorHandler.

type HealthBuilder ΒΆ

type HealthBuilder interface {
	// Health registers a health check endpoint at /health that reports the
	// application status, the build it is running and the environment.
	//
	// The health endpoint returns:
	//   - Application version and build information
	//   - Environment details (development, staging, production)
	//   - Developer contact information
	//   - Cloud platform detection (AWS, GCP, Azure, etc.)
	//   - Module revision information
	//   - HTTP 200 OK status for healthy applications
	//
	// Use cases:
	//   - Load balancer health checks
	//   - Kubernetes liveness/readiness probes
	//   - Monitoring system integration
	//   - Deployment verification
	//
	// The endpoint is registered on the application's root Router, not under
	// Prefix: a probe lives at /health whatever the API path is, which is
	// what load balancers and orchestrators expect.
	//
	// Parameters:
	//   - enableHealthEndpoint: true to enable the /health endpoint
	//   - env: Environment name (e.g., "development", "staging", "production")
	//   - developer: Developer or team contact information. It is also the
	//     value of the X-Developer response header, set on every response by
	//     the built-in router middleware, even when the endpoint is disabled.
	//
	// Examples:
	//   Health(true, "production", "api-team@company.com")
	//   Health(true, "development", "john.doe@company.com")
	//   Health(false, "", "")  // Disable health endpoint
	//
	// Returns ServiceBuilder for the next configuration step.
	Health(enableHealthEndpoint bool, env, developer string) ServiceBuilder

	// NoHealth disables the health check endpoint. This is equivalent to
	// calling Health(false, "", "").
	//
	// Use this when:
	//   - Health checks are handled by external systems
	//   - Security policies prohibit exposing application information
	//   - Custom health check implementation is preferred
	//
	// Returns ServiceBuilder for the next configuration step.
	NoHealth() ServiceBuilder
}

HealthBuilder configures a health check endpoint for monitoring, load balancers, and container orchestration platforms like Kubernetes.

type IDPayload ΒΆ

type IDPayload[T IDType] = context.IDPayload[T]

IDPayload is an alias for the `context.IDPayload[T]`: the {"id": T} body Context.Created renders for a bare identifier.

type IDType ΒΆ

type IDType = context.IDType

IDType is an alias for the `context.IDType`: the identifier types Context.Created wraps as an IDPayload.

type Initializer ΒΆ

type Initializer interface {
	Init(ctx stdContext.Context) error
}

Initializer is implemented by services registered through Builder.Services (or RegisterDependency) that need a startup step after dependency injection completes and before the server starts: cache warm-up, connection priming, background pool setup. Init runs exactly once, inside Builder.Build, in service registration order; a returned error stops the application from building. Implementations derive their own timeouts from ctx. It is the startup counterpart of Builder.Deferrables.

type JSON ΒΆ

type JSON = context.JSON

JSON the optional settings for JSON renderer.

It is an alias of the `context#JSON` type.

type JSONP ΒΆ

type JSONP = context.JSONP

JSONP the optional settings for JSONP renderer.

It is an alias of the `context#JSONP` type.

type JSONReader ΒΆ

type JSONReader = context.JSONReader

JSONReader holds the JSON decode options of the `Context.ReadJSON, ReadBody` methods.

It is an alias of the `context#JSONReader` type.

type ListFilter ΒΆ

type ListFilter = context.ListFilter

ListFilter is an alias for the `context.ListFilter`: the request half every list endpoint shares (term, names, substring and the sort request), meant to be embedded in a service's own filter.

type Map ΒΆ

type Map = context.Map

A Map is an alias of map[string]any.

type Markdown ΒΆ

type Markdown = context.Markdown

Markdown the optional settings for Markdown renderer. See `Context.Markdown` for more.

It is an alias of the `context#Markdown` type.

type MiddlewareBuilder ΒΆ

type MiddlewareBuilder interface {
	// RouterMiddlewares registers global middleware that executes for ALL requests,
	// including 404s, static files, and health checks. This middleware runs at
	// the top-level router before any route matching occurs.
	//
	// Use RouterMiddlewares for:
	//   - Request logging and metrics collection
	//   - Security headers (CORS, CSP, etc.)
	//   - Rate limiting across the entire application
	//   - Request tracing and correlation IDs
	//   - Path rewriting or request preprocessing
	//   - Global authentication checks
	//
	// Middleware execution order:
	//   1. Built-in router middleware, registered once on the first
	//      RouterMiddlewares or Middlewares call, in this order:
	//      the rest errors options handler (Errors), the access log
	//      (LogRequests/LogRequestsWith), recovery, CORS (AllowOrigin/Cors),
	//      the Server and X-Developer headers, compression (Compression),
	//      the rest errors handler (rest/errors.Handler)
	//   2. RouterMiddlewares (this method), in call order
	//   3. API middleware (Middlewares method)
	//   4. Route-specific middleware
	//   5. Route handlers
	//
	// The order of the first group is the reason the earlier steps only
	// record their configuration: the CORS rejection has to be written
	// through the Errors options and be recorded by the access log, and the
	// access log has to sit above recovery so that a panicking handler is
	// recorded too. The rest errors handler is last so that it writes
	// through the compression writer, and so that the middleware given here
	// runs inside it: a handler that rejects with a bare status, such as
	// ctx.StopWithStatus(429), answers the rest/errors envelope.
	//
	// Because the recovery middleware is registered before the middleware
	// given here, a panic raised by such a handler is recovered as well.
	//
	// Two things sit outside that net. A panic inside the access log or
	// inside the Errors options handler is raised above recovery, so
	// net/http's own per-connection recovery catches it instead: the
	// connection is dropped and the client sees no response at all. And
	// under Prefix the access log and CORS are registered on the prefixed
	// router, while the Errors handler, recovery, the Server and
	// X-Developer headers, compression and the rest errors handler are
	// application-wide - so a request to /health, outside the prefix, is
	// neither logged nor CORS'd.
	//
	// Supported middleware types:
	//   - iris.Handler functions
	//   - Dependency injection functions that return iris.Handler
	//   - Built-in Iris middleware
	//
	// Parameters:
	//   - middlewares: One or more middleware functions or handlers
	//
	// Examples:
	//   RouterMiddlewares(func(ctx iris.Context) {
	//       // Global request logging
	//       ctx.Application().Logger().Infof("Request: %s %s", ctx.Method(), ctx.Path())
	//       ctx.Next()
	//   })
	//
	//   RouterMiddlewares(func(logger *log.Logger) iris.Handler {
	//       // Middleware with dependency injection
	//       return func(ctx iris.Context) {
	//           logger.Printf("Request from IP: %s", ctx.RemoteAddr())
	//           ctx.Next()
	//       }
	//   })
	//
	//   RouterMiddlewares(
	//       securityHeaders,           // Security middleware
	//       requestTracing,            // Tracing middleware
	//       rateLimiter,              // Rate limiting
	//   )
	//
	// Returns MiddlewareBuilder for chaining additional router middleware.
	RouterMiddlewares(middlewares ...any) MiddlewareBuilder

	// Middlewares registers API-specific middleware that executes only for
	// routes registered through the API() method. This middleware runs after
	// router middleware but before individual route handlers.
	//
	// Use Middlewares for:
	//   - API authentication and authorization
	//   - Request validation specific to API routes
	//   - API versioning logic
	//   - Business logic preprocessing
	//   - API-specific rate limiting
	//   - Request/response transformation
	//
	// Middleware scope:
	//   - Applies only to routes registered via API() method
	//   - Does NOT apply to health checks, static files, or other routes
	//   - Executes after RouterMiddlewares
	//   - Can access services registered via dependency injection
	//
	// Parameters:
	//   - middlewares: One or more API-specific middleware functions
	//
	// Examples:
	//   Middlewares(func(ctx iris.Context) {
	//       // API-only authentication
	//       if !isAuthenticated(ctx) {
	//           ctx.StatusCode(401)
	//           return
	//       }
	//       ctx.Next()
	//   })
	//
	//   Middlewares(func(authService *AuthService) iris.Handler {
	//       // Authentication with injected service
	//       return func(ctx iris.Context) {
	//           user, err := authService.ValidateToken(ctx)
	//           if err != nil {
	//               ctx.StatusCode(401)
	//               return
	//           }
	//           ctx.Values().Set("user", user)
	//           ctx.Next()
	//       }
	//   })
	//
	// Returns APIBuilder for the final configuration step.
	Middlewares(middlewares ...any) APIBuilder
}

MiddlewareBuilder configures the middleware pipeline with clear separation between global middleware (RouterMiddlewares) and API-specific middleware (Middlewares).

type N ΒΆ

type N = context.N

N is a struct which can be passed on the `Context.Negotiate` method. It contains fields which should be filled based on the `Context.Negotiation()` server side values. If no matched mime then its "Other" field will be sent, which should be a string or []byte. It completes the `context/context.ContentSelector` interface.

An alias for the `context.N`.

type NgrokOptions ΒΆ

type NgrokOptions = server.NgrokOptions

NgrokOptions is a type alias for the `server.NgrokOptions`.

type Options ΒΆ

type Options struct {
	// Name is the application name and the log prefix for
	// that Application instance's Logger.
	Name string `ini:"name" json:"name" yaml:"Name" toml:"Name"`

	// LogLevel determines the level of logging used by the application to output messages.
	// The logger is used mostly during the build state, but may also output debug error messages at runtime,
	// such as when malformed data structures are sent to the client (e.g., Context.JSON/JSONP/XML...).
	// Default: "info".
	// Possible values: "disable", "fatal", "error", "warn", "info", "debug".
	LogLevel string `ini:"log_level" json:"log_level" yaml:"LogLevel" toml:"LogLevel"`

	// Host specifies the trusted domain on which the server should run.
	// It is read back from Options.Host and, per request, from Context.Host;
	// the router uses it for subdomain matching.
	// Example: "iris-go.com".
	Host string `ini:"host" json:"host" yaml:"Host" toml:"Host"`

	// DisableFatalRun keeps Run and Listen from exiting the process when the
	// server fails to start or stops with an error: the failure is logged at
	// error level and returned to the caller instead. Set it in a process that
	// runs more than one server, or in a test that starts a real listener.
	// Default: false, a failed Run logs at fatal level and exits with status 1.
	DisableFatalRun bool `ini:"disable_fatal_run" json:"disable_fatal_run" yaml:"DisableFatalRun" toml:"DisableFatalRun"`

	// Router configures the router for all routes
	Router RouterOptions `ini:"router" json:"router,omitempty" yaml:"Router" toml:"Router"`

	// Context configures request and response handling for all routes, overwrites the defaults.
	//
	// A child Router (Application.Router, Subdomain) copies these when it is
	// created, so a later Application.EditOptions reaches the root Router only:
	// configure the context options before registering any child Router.
	Context context.ContextOptions `ini:"context" json:"context,omitempty" yaml:"Context" toml:"Context"`
}

Options is the configuration for the Iris Application. Includes server & handler timeout, router, request and response options too. All fields are optional.

Usage:

app := iris.New(iris.Options{...})

func YAML ΒΆ

func YAML(optionsFilename string) Options

YAML reads the configuration from a YAML file. The file should contain the configuration for the Options structure. The file should be in the following format:

Name: "My Application"
LogLevel: "info"
Host: "iris-go.com"
[...]

The YAML keys are the field names as they are declared in the Options structure (they are matched exactly, they are not case-insensitive).

Returns an instance of the Options structure which completes the Configurator interface.

func (*Options) Bind ΒΆ

func (opts *Options) Bind(filename string) error

Bind reads the configuration from the "SERVER_CONFIG" environment variable in form of YAML or from a file and sets it to the Options structure.

func (Options) Configure ΒΆ

func (opts Options) Configure(app *Application)

Configure sets the configuration for the Iris Application. Unset (zero) fields are filled from the defaults: a partial Options literal configures only what it sets, it does not zero the rest.

func (*Options) SetHost ΒΆ

func (opts *Options) SetHost(host string)

SetHost sets the host for the Iris Application, it also sets the host for the router.

type Page ΒΆ

type Page[T any] = context.Page[T]

Page is an alias for the `context.Page[T]`: the paginated response envelope of Context.Paginated and context.NewPage.

func NewPage ΒΆ

func NewPage[T any](opts PageOptions, filter any, items []T, totalCount int64) *Page[T]

NewPage returns a new paginated response envelope for the given page options, filter, items and total count. It forwards to `context.NewPage`; a generic function cannot be a type alias, so this is a wrapper, not an alias like `iris.Page[T]` itself.

Use it when a handler builds the envelope on its own; Context.Paginated already returns one.

type PageOptions ΒΆ

type PageOptions = context.PageOptions

PageOptions is an alias for the `context.PageOptions`: the page/size/details a client sends through the URL query, read by Context.BindPagination and Context.Paginated.

type PaginationOption ΒΆ

type PaginationOption = context.PaginationOption

PaginationOption is an alias for the `context.PaginationOption`: the option type of Context.BindPagination and Context.Paginated. See AllowSort and DenySort.

type QueryOption ΒΆ

type QueryOption = context.QueryOption

QueryOption is an alias for the `context.QueryOption`: the option type of the strict query readers Context.QueryDate, Context.QueryInt and Context.QueryBool. See QueryRequired, QueryDefault and QueryZeroValues.

type RequestLoggingBuilder ΒΆ

type RequestLoggingBuilder interface {
	// LogRequests logs every request and response as structured JSON, which is
	// what makes traffic readable to both a log pipeline and a person.
	//
	// The access log captures:
	//   - Request details: method, path, headers, body
	//   - Response details: status code, headers, body, latency
	//   - Client information: IP address, user agent
	//   - Timing information: request duration, timestamps
	//   - Error details: panic logs, error traces
	//
	// Output destinations:
	//   - File: access_log.json (automatically created)
	//   - Console: stdout (can be disabled by modifying the middleware)
	//
	// Parameters:
	//   - enableRequestAccessLog: true to enable logging, false to disable
	//
	// Example:
	//   LogRequests(true)   // Enable for development and production monitoring
	//   LogRequests(false)  // Disable for performance-critical scenarios
	//
	// Returns HealthBuilder for the next configuration step.
	LogRequests(enableRequestAccessLog bool) HealthBuilder

	// LogRequestsWith registers the given pre-configured access log
	// middleware and its closer. Use it when the tuned defaults of
	// LogRequests(true) do not fit: custom output, formatter, fields.
	//
	//   ac := accesslog.File("access_log.json")
	//   ac.AddFields(func(ctx iris.Context, f *accesslog.Fields) { ... })
	//   builder.LogRequestsWith(ac)
	//
	// LogRequests(true) is a shortcut for LogRequestsWith with the
	// framework's tuned default configuration. A nil value is ignored.
	//
	// Returns HealthBuilder for the next configuration step.
	LogRequestsWith(ac *accesslog.AccessLog) HealthBuilder
}

RequestLoggingBuilder configures structured request/response logging for observability, debugging, and compliance requirements.

type Router ΒΆ

type Router = router.Router

Router is just a group joiner of routes which have the same prefix and share same middleware(s) also. Router could also be named as 'Join' or 'Node' or 'Group' , Router chosen because it is fun.

Look the `core/router#RouterBuilder` for its implementation.

A shortcut for the `core/router#Router`, the type a controller's Routing method and a Router("/path", func(iris.Router)) callback receive.

type RouterOptions ΒΆ

type RouterOptions = router.RouterOptions

RouterOptions is a type alias for the `router.RouterOptions`.

type Routing ΒΆ

type Routing = router.Routing

Routing is a type alias for the `core/router#Routing`.

type ServerOptions ΒΆ

type ServerOptions = server.ServerOptions

ServerOptions is a type alias for the `server.ServerOptions`.

type ServiceBuilder ΒΆ

type ServiceBuilder interface {
	// Errors configures centralized error handling with custom error mappings,
	// status codes, and response formats for consistent API error responses.
	//
	// The errors system provides:
	//   - Automatic error code mapping (database errors β†’ HTTP status codes)
	//   - Structured error responses with details and correlation IDs
	//   - Custom error handlers for specific error types
	//   - Integration with logging and monitoring systems
	//
	// Common error mappings:
	//   - sql.ErrNoRows β†’ 404 Not Found
	//   - validation errors β†’ 400 Bad Request
	//   - authentication errors β†’ 401 Unauthorized
	//   - authorization errors β†’ 403 Forbidden
	//
	// Parameters:
	//   - options: Error handling configuration from errors.NewOptions()
	//
	// Example:
	//   Errors(errors.NewOptions().
	//       MapErrors(errors.NotFound, sql.ErrNoRows).
	//       MapErrors(errors.Unavailable, driver.ErrBadConn).
	//       MapErrorFunc(errors.DeadlineExceeded, func(err error) error {
	//           // Return an error to answer with this code, nil to pass.
	//           if stdErrors.Is(err, stdContext.DeadlineExceeded) {
	//               return fmt.Errorf("the database took too long: %w", err)
	//           }
	//           return nil
	//       }))
	//
	// Returns ServiceBuilder for chaining.
	Errors(*errors.Options) ServiceBuilder

	// Deferrables registers cleanup functions that will be executed when
	// the server shuts down gracefully. This ensures proper resource cleanup.
	//
	// Supported values (stdContext is the standard library's "context" package):
	//   - func()                         // Simple cleanup function
	//   - func() error                   // Cleanup with error handling
	//   - func(stdContext.Context)       // Cleanup which respects the shutdown context
	//   - func(stdContext.Context) error // Both of the above
	//   - interface{ Close() error }     // Objects with Close method returning error (io.Closer)
	//   - interface{ CloseWithContext(stdContext.Context) error } // Context-aware closers
	//
	// Any other value panics at registration time. An object with a plain
	// Close() method (no error return) is not accepted, pass its method
	// instead: Deferrables(worker.Close).
	//
	// Common use cases:
	//   - Closing database connections
	//   - Stopping background workers
	//   - Flushing caches or logs
	//   - Releasing external resources
	//
	// Parameters:
	//   - closers: One or more cleanup functions or closable objects
	//
	// Examples:
	//   Deferrables(func() { db.Close() })
	//   Deferrables(redisClient, elasticClient)  // Objects with a Close() error method
	//   Deferrables(
	//       func() { worker.Stop() },
	//       func() error { return cache.Flush() },
	//   )
	//
	// Returns ServiceBuilder for chaining.
	Deferrables(closers ...any) ServiceBuilder

	// Services registers dependencies for dependency injection throughout the
	// application. These dependencies can be used in controllers, middleware,
	// and other components.
	//
	// Dependency types supported:
	//   - Service instances (databases, repositories, business services)
	//   - Configuration objects
	//   - Third-party clients (Redis, Elasticsearch, etc.)
	//   - Iris Configurators for advanced application setup
	//   - Functions that return services (factories)
	//
	// Dependency injection features:
	//   - Automatic constructor injection based on parameter types
	//   - Singleton lifecycle management
	//   - Interface-based dependency resolution
	//
	// Three values are treated specially:
	//   - a value with a Close() or Close() error method is registered as a
	//     dependency AND its Close is added to the shutdown closers, so it
	//     does not need a second Deferrables call;
	//   - an iris.Worker is registered as a dependency AND started after the
	//     initializers, then stopped at shutdown; when it is a closer too it
	//     is stopped before it is closed. See iris.Worker;
	//   - an iris.Configurator is applied to the application immediately and
	//     is not registered as a dependency.
	//
	// A func() or a func() error returns nothing injectable and panics
	// here: pass it to Deferrables for cleanup, or implement
	// iris.Initializer for startup work.
	//
	// Parameters:
	//   - dependencies: Services, configurations, or factories to register
	//
	// Examples:
	//   Services(
	//       database.New(config.DatabaseURL),      // Database service
	//       repository.NewUserRepo,                // Repository factory
	//       service.NewAuthService,                // Business service factory
	//       &config.AppConfig{},                   // Configuration object
	//       redis.NewClient(&redis.Options{}),     // Third-party client
	//   )
	//
	// Returns MiddlewareBuilder for the next configuration step.
	Services(dependencies ...any) MiddlewareBuilder
}

ServiceBuilder configures error handling, dependency injection and graceful shutdown: the three parts of an application's lifecycle.

type SimpleUser ΒΆ

type SimpleUser = context.SimpleUser

SimpleUser is a simple implementation of the User interface.

type TimeoutOptions ΒΆ

type TimeoutOptions = server.TimeoutOptions

TimeoutOptions is a type alias for the `server.TimeoutOptions`.

type UnmarshalerFunc ΒΆ

type UnmarshalerFunc = context.UnmarshalerFunc

UnmarshalerFunc a shortcut, an alias for the `context#UnmarshalerFunc` type which implements the `context#Unmarshaler` interface for reading request's body via custom decoders, most of them already implement the `context#UnmarshalerFunc` like the json.Unmarshal, xml.Unmarshal, yaml.Unmarshal and every library which follows the best practises and is aligned with the Go standards.

See 'context#UnmarshalBody` for more.

type User ΒΆ

type User = context.User

User is a generic view of an authorized client. See `Context.User` and `SetUser` methods for more. An alias for the `context/User` type.

type Validatable ΒΆ

type Validatable = context.Validatable

Validatable is an alias for the `context.Validatable`: implemented by request types that validate themselves after decoding; Context.BindJSON and its variants call Validate and reject the request on a non-nil error.

type Worker ΒΆ

type Worker interface {
	// Run blocks until the given context is done or the work fails. The
	// context is cancelled at shutdown, just before Stop is called.
	//
	// An error returned before shutdown is logged with the worker's type name
	// and nothing else: a failed worker does not take the HTTP server with it.
	Run(ctx stdContext.Context) error
	// Stop releases what Run acquired. It is called once, at shutdown, with a
	// bounded context: the Application.Shutdown context when that one carries
	// a deadline, otherwise a ten second one, so a Stop which hangs cannot
	// hold the process open forever.
	//
	// Shutdown then waits for Run to return, within the same budget, so a
	// worker is really finished when Shutdown reports success. A Run which
	// does not return in time is logged and reported as a shutdown error.
	//
	// That ten second budget is per worker, not per shutdown: the closers run
	// one after another, so N stuck workers cost N times ten seconds. Pass a
	// deadline to Application.Shutdown to bound the whole chain instead; a
	// caller-supplied deadline is used as it is and is shared by every closer.
	Stop(ctx stdContext.Context) error
}

Worker is implemented by a long-running service registered through Builder.Services: a scheduler, a queue consumer, a cache refresher. The builder starts it after every Initializer has returned and stops it before the closers run, so it lives inside the startup and shutdown chain the builder already enforces instead of in a goroutine next to it.

A Worker is registered as a dependency too, exactly like a value with a Close method is, so the same value can be injected into controllers.

It is the long-running counterpart of Initializer.

type XML ΒΆ

type XML = context.XML

XML the optional settings for XML renderer.

It is an alias of the `context#XML` type.

Directories ΒΆ

Path Synopsis
_examples
01-getting-started/01-hello-world command
Step 1 of 13: the smallest Iris program.
Step 1 of 13: the smallest Iris program.
01-getting-started/02-routes-and-params command
Step 2 of 13: routes, a router prefix and a typed path parameter.
Step 2 of 13: routes, a router prefix and a typed path parameter.
01-getting-started/03-json-and-validation command
Step 3 of 13: a JSON body, validated before the handler sees it.
Step 3 of 13: a JSON body, validated before the handler sees it.
01-getting-started/04-errors-mapped-once command
Step 4 of 13: domain errors, mapped to status codes exactly once.
Step 4 of 13: domain errors, mapped to status codes exactly once.
01-getting-started/05-storage-behind-an-interface command
Step 5 of 13: storage behind an interface, rules in a service.
Step 5 of 13: storage behind an interface, rules in a service.
01-getting-started/06-controllers command
Step 6 of 13: a controller instead of closures.
Step 6 of 13: a controller instead of closures.
01-getting-started/07-nested-routes-and-guards command
Step 7 of 13: books under shelves, with guards.
Step 7 of 13: books under shelves, with guards.
01-getting-started/08-pagination command
Step 8 of 13: a paginated list in one call.
Step 8 of 13: a paginated list in one call.
01-getting-started/09-middleware command
Step 9 of 13: a middleware, and where it runs.
Step 9 of 13: a middleware, and where it runs.
01-getting-started/10-admin-and-basicauth command
Step 10 of 13: an admin group behind basic authentication.
Step 10 of 13: an admin group behind basic authentication.
01-getting-started/11-configuration command
Step 11 of 13: configuration from a file, secrets from the environment.
Step 11 of 13: configuration from a file, secrets from the environment.
01-getting-started/12-newbuilder command
Step 12 of 13: the whole application on the iris.NewBuilder chain.
Step 12 of 13: the whole application on the iris.NewBuilder chain.
01-getting-started/13-testing command
Step 13 of 13: the whole service tested in memory.
Step 13 of 13: the whole service tested in memory.
02-routing/custom-macro command
Custom path macros: a new constraint on a built-in parameter type, and a parameter type of your own.
Custom path macros: a new constraint on a built-in parameter type, and a parameter type of your own.
02-routing/groups command
Route groups: child routers that inherit a path prefix and middleware.
Route groups: child routers that inherit a path prefix and middleware.
02-routing/path-parameters command
Path parameters: typed macros in the route pattern, typed accessors in the handler.
Path parameters: typed macros in the route pattern, typed accessors in the handler.
02-routing/routing-basics command
Routing basics: one function per HTTP method, and the Context helpers that carry the status code and the error branch for you.
Routing basics: one function per HTTP method, and the Context helpers that carry the status code and the error branch for you.
02-routing/subdomains command
Subdomain routing: a router bound to a host label instead of a path prefix.
Subdomain routing: a router bound to a host label instead of a path prefix.
02-routing/wrap-router command
Wrapping the router: raw net/http code that runs before any route matching.
Wrapping the router: raw net/http code that runs before any route matching.
03-controllers/basic command
Controllers: a constructor and a Routing method, mounted with app.Router.
Controllers: a constructor and a Routing method, mounted with app.Router.
03-controllers/mvc-generics command
Generic MVC controllers: five typed methods, the REST routes generated.
Generic MVC controllers: five typed methods, the REST routes generated.
03-controllers/nested-guards command
Nested controllers and the two guard idioms: a group guard for every route and a positional guard for single routes.
Nested controllers and the two guard idioms: a group guard for every route and a positional guard for single routes.
03-controllers/repository command
mvc.UseRepository: the six resource routes over a repository, with no controller in between.
mvc.UseRepository: the six resource routes over a repository, with no controller in between.
04-request/body-limits command
Capping request body size, app-wide and per route.
Capping request body size, app-wide and per route.
04-request/pagination command
A complete list endpoint in one call: ctx.Paginated.
A complete list endpoint in one call: ctx.Paginated.
04-request/query-and-forms command
Query strings and form bodies: the two places where client input arrives as loose key/value pairs.
Query strings and form bodies: the two places where client input arrives as loose key/value pairs.
04-request/raw-body command
ctx.ReadBody: the raw body, and one struct for every content type.
ctx.ReadBody: the raw body, and one struct for every content type.
04-request/read-json-optional command
An optional JSON request body with ctx.BindJSONOptional[T].
An optional JSON request body with ctx.BindJSONOptional[T].
04-request/read-json-validate command
Reading and validating a JSON body with ctx.BindJSON[T].
Reading and validating a JSON body with ctx.BindJSON[T].
04-request/strict-query command
Query parameters that refuse to be wrong, and partial updates that refuse to be silent.
Query parameters that refuse to be wrong, and partial updates that refuse to be silent.
04-request/uploads command
Multipart file uploads.
Multipart file uploads.
05-response/content-negotiation command
Content negotiation: one URL, several representations.
Content negotiation: one URL, several representations.
05-response/files command
File responses: inline, attachment, in-memory and rate-limited.
File responses: inline, attachment, in-memory and rate-limited.
05-response/rest-helpers command
The typed response helpers: one contract, ctx.Helper(value, err).
The typed response helpers: one contract, ctx.Helper(value, err).
05-response/streaming-ai command
One ai.Open handler that streams a model's answer or returns it as a single JSON document.
One ai.Open handler that streams a model's answer or returns it as a single JSON document.
05-response/streaming-sse command
Server-Sent Events with the sse package.
Server-Sent Events with the sse package.
05-response/writers command
The Context response writers: one format per route.
The Context response writers: one format per route.
06-middleware/accesslog command
Access logging: one structured record per request, with your own fields.
Access logging: one structured record per request, with your own fields.
06-middleware/cache command
Caching on two layers: client caching headers and server-side response caching.
Caching on two layers: client caching headers and server-side response caching.
06-middleware/conditional command
Conditional middleware: a debug bundle that runs only when the request asks for it.
Conditional middleware: a debug bundle that runs only when the request asks for it.
06-middleware/cors command
CORS: allowed origins, answered preflights and a JSON body for rejected origins.
CORS: allowed origins, answered preflights and a JSON body for rejected origins.
06-middleware/error-middleware command
Middleware that returns an error instead of writing a response.
Middleware that returns an error instead of writing a response.
06-middleware/i18n command
Internationalization: one message catalog, one language per request.
Internationalization: one message catalog, one language per request.
06-middleware/rate-limit command
Rate limiting: token buckets per authenticated principal, with Retry-After on rejection.
Rate limiting: token buckets per authenticated principal, with Retry-After on rejection.
06-middleware/request-id command
Request IDs: one identifier per request, in the response header and the logs.
Request IDs: one identifier per request, in the response header and the logs.
06-middleware/writing-middleware command
Writing your own middleware: a timing factory and two guards, each registered where its scope belongs.
Writing your own middleware: a timing factory and two guards, each registered where its scope belongs.
07-dependency-injection/constructors command
Constructor injection: a value, constructor functions and an interface parameter matched by method set.
Constructor injection: a value, constructor functions and an interface parameter matched by method set.
07-dependency-injection/handler-func command
HandlerFunc: dependency injection for plain handlers and middleware.
HandlerFunc: dependency injection for plain handlers and middleware.
07-dependency-injection/initializer command
Service lifecycle: iris.Initializer at startup, closers at shutdown.
Service lifecycle: iris.Initializer at startup, closers at shutdown.
07-dependency-injection/request-scoped command
Request-scoped dependencies: the function itself is injected, not its result.
Request-scoped dependencies: the function itself is injected, not its result.
08-errors/central-error-map command
The central error map: domain sentinels classified in one place.
The central error map: domain sentinels classified in one place.
08-errors/error-router command
errors.Router: handlers and middleware that return their errors.
errors.Router: handlers and middleware that return their errors.
08-errors/handle-errorf command
errors.HandleErrorf: keep the classification, add the call site.
errors.HandleErrorf: keep the classification, add the call site.
08-errors/validation-errors command
Field validation, end to end: Validate + validation.Join -> wire format.
Field validation, end to end: Validate + validation.Join -> wire format.
09-authentication/api-key command
API keys: authenticating a service, a cron job or a webhook sender.
API keys: authenticating a service, a cron job or a webhook sender.
09-authentication/auth-sdk command
The auth SDK: auth.Auth[T] with a provider, ready-made token handlers and per-router verification.
The auth SDK: auth.Auth[T] with a provider, ready-made token handlers and per-router verification.
09-authentication/basicauth command
HTTP Basic Authentication for an admin group.
HTTP Basic Authentication for an admin group.
09-authentication/jwt-middleware command
The jwt middleware: a Signer/Verifier round trip.
The jwt middleware: a Signer/Verifier round trip.
09-authentication/sessions command
Typed sessions with the v14 secure defaults.
Typed sessions with the v14 secure defaults.
10-configuration/configuration command
Configuration: one YAML document for the framework and for your own settings, secrets from the environment only, and the merge that makes a partial configuration safe.
Configuration: one YAML document for the framework and for your own settings, secrets from the environment only, and the merge that makes a partial configuration safe.
10-configuration/configuration-worker command
The service's own configuration file, and a background worker the framework starts and stops for you.
The service's own configuration file, and a background worker the framework starts and stops for you.
11-views/templates command
HTML pages from templates, with a shared layout.
HTML pages from templates, with a shared layout.
12-database/pg-crud command
A real database behind the repository seam: kataras/pg, with its errors mapped to HTTP.
A real database behind the repository seam: kataras/pg, with its errors mapped to HTTP.
12-database/postgres-mapping command
PostgreSQL error mapping: one blank import turns the driver's errors into 404, 409 and 400.
PostgreSQL error mapping: one blank import turns the driver's errors into 404, 409 and 400.
13-websockets/chat command
A chat room over WebSockets.
A chat room over WebSockets.
14-testing/iris-httptest command
A tasks API tested in main_test.go with the framework's own github.com/kataras/iris/v14/httptest package.
A tasks API tested in main_test.go with the framework's own github.com/kataras/iris/v14/httptest package.
14-testing/std-httptest command
The same tasks API, tested in main_test.go with nothing but the standard library: net/http/httptest, encoding/json and testing.
The same tasks API, tested in main_test.go with nothing but the standard library: net/http/httptest, encoding/json and testing.
15-production/graceful-shutdown command
Graceful shutdown: what runs when the process is interrupted, in which order, and how long the server waits for in-flight requests.
Graceful shutdown: what runs when the process is interrupted, in which order, and how long the server waits for in-flight requests.
15-production/observability command
Observability endpoints: the live process dashboard, the Go profiler, the expvar gauges the dashboard publishes, and per-request cost measurement.
Observability endpoints: the live process dashboard, the Go profiler, the expvar gauges the dashboard publishes, and per-request cost measurement.
15-production/serving-and-tls command
Serving: app.Listen for the plain case, app.Run(iris.ServerOptions{...}) when you need TLS, Let's Encrypt or server tuning.
Serving: app.Listen for the plain case, app.Run(iris.ServerOptions{...}) when you need TLS, Let's Encrypt or server tuning.
16-advanced/ai-gateway command
An AI gateway: relaying an upstream provider stream, with failover.
An AI gateway: relaying an upstream provider stream, with failover.
16-advanced/api-graph command
The apigraph controller: an interactive D3.js map of every registered route, mounted behind an admin guard.
The apigraph controller: an interactive D3.js map of every registered route, mounted behind an admin guard.
16-advanced/file-server command
Static file serving with the fileserver controller, hardened with the BlockHidden asset validator.
Static file serving with the fileserver controller, hardened with the BlockHidden asset validator.
16-advanced/multi-app command
Multi-application composition: two independent Iris applications served behind a single listener through apps.Switch.
Multi-application composition: two independent Iris applications served behind a single listener through apps.Switch.
16-advanced/patches command
Global patches: replacing framework defaults through iris.Patches().
Global patches: replacing framework defaults through iris.Patches().
16-advanced/sitemap command
The sitemap controller: /sitemap.xml built from the registered static routes when the application is built.
The sitemap controller: /sitemap.xml built from the registered static routes when the application is built.
16-advanced/std-interop command
Standard library interop: net/http handlers inside Iris, and the Iris application inside a plain http.Server.
Standard library interop: net/http handlers inside Iris, and the Iris application inside a plain http.Server.
16-advanced/typed-context command
Custom typed contexts: handlers written against your own context type through iris.NewContextWrapper.
Custom typed contexts: handlers written against your own context type through iris.NewContextWrapper.
Package ai renders and relays AI model streams over HTTP.
Package ai renders and relays AI model streams over HTTP.
Package apps is responsible to control many Iris Applications.
Package apps is responsible to control many Iris Applications.
Package auth provides generic, token-based authentication for Iris applications.
Package auth provides generic, token-based authentication for Iris applications.
oauth2
Package oauth2 provides an implementation of OAuth2 server-related logic, including the registration and retrieval of clients, authorization codes, device codes, tokens, and consent handling.
Package oauth2 provides an implementation of OAuth2 server-related logic, including the registration and retrieval of clients, authorization codes, device codes, tokens, and consent handling.
oauth2/opa
Open Policy Agent (OPA) is an open-source, general-purpose policy engine that enables unified, context-aware policy enforcement across the stack.
Open Policy Agent (OPA) is an open-source, general-purpose policy engine that enables unified, context-aware policy enforcement across the stack.
Package client is an HTTP client for sending requests to remote services and decoding their responses.
Package client is an HTTP client for sending requests to remote services and decoding their responses.
This file exists for its name.
This file exists for its name.
controller
fileserver
Package fileserver serves static files from a directory, an embed.FS or any fs.FS, through the New controller or the Handler function.
Package fileserver serves static files from a directory, an embed.FS or any fs.FS, through the New controller or the Handler function.
mvc
core
dep
pkg/constraints
Package constraints defines the type sets the framework's generic code is bounded by.
Package constraints defines the type sets the framework's generic code is bounded by.
pkg/jsonutil
Package jsonutil is the single source of the framework's encoding/json/v2 policy.
Package jsonutil is the single source of the framework's encoding/json/v2 policy.
pkg/pagination
Package pagination holds the data types of a paginated list: the page options a client sends in the URL, the page envelope a server answers with and the list filter both share.
Package pagination holds the data types of a paginated list: the page options a client sends in the URL, the page envelope a server answers with and the list filter both share.
pkg/uid
Package uid provides tiny helpers over the standard library's uuid package for the two id shapes the framework generates: unpredictable version 4 ids and time-ordered version 7 ids.
Package uid provides tiny helpers over the standard library's uuid package for the two id shapes the framework generates: unpredictable version 4 ids and time-ordered version 7 ids.
router/macro/handler
Package handler is the highest level module of the macro package which makes use the rest of the macro package, it is mainly used, internally, by the router package.
Package handler is the highest level module of the macro package which makes use the rest of the macro package, it is mainly used, internally, by the router package.
server/ngrok
Package ngrok opens ngrok tunnels for the Iris server.
Package ngrok opens ngrok tunnels for the Iris server.
internal
mimetypes
Package mimetypes provides an extended file-extension to MIME type lookup and, via its init, registers that extended table into the standard library's mime package so that mime.TypeByExtension resolves the additional types too.
Package mimetypes provides an extended file-extension to MIME type lookup and, via its init, registers that extended table into the standard library's mime package so that mime.TypeByExtension resolves the additional types too.
middleware
accesslog
Package accesslog logs one line per request, in a text, CSV, JSON or custom template format, to one or more destinations.
Package accesslog logs one line per request, in a text, CSV, JSON or custom template format, to one or more destinations.
apikey
Package apikey guards routes with a shared secret that a caller presents on every request, which is how services, cron jobs and webhooks authenticate to each other when there is no user to sign in.
Package apikey guards routes with a shared secret that a caller presents on every request, which is how services, cron jobs and webhooks authenticate to each other when there is no user to sign in.
basicauth
Package basicauth implements HTTP Basic Authentication (RFC 7617).
Package basicauth implements HTTP Basic Authentication (RFC 7617).
bodylimit
Package bodylimit caps the size of a request body.
Package bodylimit caps the size of a request body.
cache
Package cache sets client- and proxy-cache headers (Cache-Control, ETag, Last-Modified, Expires, Pragma, Vary, Proxy-Authenticate) on the response.
Package cache sets client- and proxy-cache headers (Cache-Control, ETag, Last-Modified, Expires, Pragma, Vary, Proxy-Authenticate) on the response.
cache/httpcache
Package httpcache provides a middleware for caching HTTP responses in DragonflyDB or Redis.
Package httpcache provides a middleware for caching HTTP responses in DragonflyDB or Redis.
compress
Package compress negotiates gzip, deflate, brotli, snappy, s2 and zstd for the response and transparently decompresses a compressed request body.
Package compress negotiates gzip, deflate, brotli, snappy, s2 and zstd for the response and transparently decompresses a compressed request body.
cors
Package cors implements Cross-Origin Resource Sharing.
Package cors implements Cross-Origin Resource Sharing.
counter
Package counter counts requests (or anything else) with an atomic, generic-typed counter.
Package counter counts requests (or anything else) with an atomic, generic-typed counter.
geolocation
Package geolocation resolves the client's IP address to a country, region and city (and, optionally, the country's main language).
Package geolocation resolves the client's IP address to a country, region and city (and, optionally, the country's main language).
grpc
Package grpc serves a gRPC (or gRPC-Web) server through an Iris route.
Package grpc serves a gRPC (or gRPC-Web) server through an Iris route.
hcaptcha
Package hcaptcha verifies the hCaptcha answer that a form submission carries.
Package hcaptcha verifies the hCaptcha answer that a form submission carries.
httpcost
Package httpcost measures the CPU, memory and time cost of serving a request.
Package httpcost measures the CPU, memory and time cost of serving a request.
i18n
Package i18n provides internalization and localization features for Iris.
Package i18n provides internalization and localization features for Iris.
ipaccess
Package ipaccess allows or blocks requests by the client's IP address, given as literals, CIDR blocks or ranges.
Package ipaccess allows or blocks requests by the client's IP address, given as literals, CIDR blocks or ranges.
jwt
Package jwt signs and verifies JSON Web Tokens.
Package jwt signs and verifies JSON Web Tokens.
methodoverride
Package methodoverride lets clients that cannot issue PUT, PATCH or DELETE send a POST carrying the intended method instead.
Package methodoverride lets clients that cannot issue PUT, PATCH or DELETE send a POST carrying the intended method instead.
modrevision
Package modrevision serves the build information of the running binary (module version, VCS revision, build time) on a route.
Package modrevision serves the build information of the running binary (module version, VCS revision, build time) on a route.
monitor
Package monitor reports live process and system statistics (CPU, memory, goroutines, uptime) as JSON and as a small HTML dashboard.
Package monitor reports live process and system statistics (CPU, memory, goroutines, uptime) as JSON and as a small HTML dashboard.
pprof
Package pprof provides native pprof support via middleware.
Package pprof provides native pprof support via middleware.
rate
Package rate implements a token-bucket rate limiter for incoming requests, one bucket per client.
Package rate implements a token-bucket rate limiter for incoming requests, one bucket per client.
recaptcha
Package recaptcha verifies the Google reCAPTCHA answer that a form submission carries.
Package recaptcha verifies the Google reCAPTCHA answer that a form submission carries.
recorder
Package recorder keeps a copy of the request body, the response body, or both, so that a later handler can read them again.
Package recorder keeps a copy of the request body, the response body, or both, so that a later handler can read them again.
recovery
Package recovery turns a panic in a handler into a 500 response instead of a crashed server.
Package recovery turns a panic in a handler into a 500 response instead of a crashed server.
referrer
Package referrer parses the request's Referer header into its source type (direct, search, social, email or indirect) and stores it on the Context.
Package referrer parses the request's Referer header into its source type (direct, search, social, email or indirect) and stores it on the Context.
requestid
Package requestid assigns an ID to every request and exposes it through Context.ID, the "X-Request-Id" header and the `Get` function.
Package requestid assigns an ID to every request and exposes it through Context.ID, the "X-Request-Id" header and the `Get` function.
rewrite
Package rewrite redirects or rewrites requests according to a list of regular-expression rules, and can force a primary subdomain such as "www".
Package rewrite redirects or rewrites requests according to a list of regular-expression rules, and can force a primary subdomain such as "www".
servertiming
Package servertiming provides middleware for the Iris Web Framework to add Server-Timing headers to HTTP responses.
Package servertiming provides middleware for the Iris Web Framework to add Server-Timing headers to HTTP responses.
sessions
Package sessions provides typed HTTP sessions backed by a cookie, Redis or a SQL database.
Package sessions provides typed HTTP sessions backed by a cookie, Redis or a SQL database.
versioning
Package versioning routes a request to a handler by the API version it asks for, through the Accept-Version header, the Accept header or a custom source.
Package versioning routes a request to a handler by the API version it asks for, through the Accept-Version header, the Accept header or a custom source.
view
Package view registers a template engine so that Render, WithTemplate and Context.Render can render its templates.
Package view registers a template engine so that Render, WithTemplate and Context.Render can render its templates.
websocket
Package websocket bridges the neffos websocket server with Iris.
Package websocket bridges the neffos websocket server with Iris.
rest
errors
This file installs the canonical RestErrorRenderer of the Context's typed binding/response methods (BindJSON, BindParams, Count, Paginated, ...).
This file installs the canonical RestErrorRenderer of the Context's typed binding/response methods (BindJSON, BindParams, Count, Paginated, ...).
errors/pgerrors
Package pgerrors restores the PostgreSQL-specific error mapping of the rest/errors package.
Package pgerrors restores the PostgreSQL-specific error mapping of the rest/errors package.
errors/validation
Package validation provides generic field validation utilities for the Iris web framework.
Package validation provides generic field validation utilities for the Iris web framework.
Package sse implements Server-Sent Events for Iris, in both directions: a push-based response stream, and a tolerant reader for consuming somebody else's.
Package sse implements Server-Sent Events for Iris, in both directions: a push-based response stream, and a tolerant reader for consuming somebody else's.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL