middleware/

directory
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

README

Middleware

The Iris web framework provides a variety of built-in middleware handlers to extend and enhance your application. Middleware handlers are functions that can intercept and process incoming HTTP requests before they reach your application's routes. They can perform tasks such as logging, authentication, rate limiting, and more. Middleware is just a func(iris.Context) which runs before (or after) the main route's handler. Example of a middleware handler:

package main

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

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

    // Register a custom middleware handler.
    app.Use(func(ctx iris.Context) {
        ctx.Application().Logger().Infof("Request received: %s", ctx.Path())
        ctx.Next()
    })

    app.Get("/", func(ctx iris.Context) {
        ctx.HTML("Hello, world!")
    })

    app.Listen(":8080")
}

Use app.Use to apply middleware for all routes, including 404s and 405s. Use childRouter.Use to apply it for sub-routes only, excluding 404s and 405s. Use app.UseRouter to register middleware before the routing process (where you can modify request parts such as the URL path), or attach it directly to specific routes with app.Get, app.Post, and so on.

Built-in Middleware

Middleware Description Documentation
AccessLog The AccessLog middleware provides configurable access logging for your application. It records incoming HTTP requests and responses for traffic monitoring, debugging and audits. The log format and output destination are configurable. accesslog/README
API Key The API Key middleware guards routes with a shared secret that the caller presents on every request, which is how services, cron jobs and webhooks authenticate when there is no user to sign in. Keys are compared in constant time, may be stored as hashes or resolved from a database, and the principal that matched is available to the handlers. apikey/README
Basic Authentication The Basic Authentication middleware implements HTTP Basic Authentication as defined in RFC 7617. It secures your routes by requiring clients to provide a username and password with each request. This is a simple way to protect endpoints or restrict access to certain parts of your application. basicauth/README
Request Body Limit The Request Body Limit middleware caps the size of incoming request bodies. It helps prevent resource exhaustion attacks by rejecting requests that exceed the specified limit. bodylimit/README
Cache The Cache middleware enables caching of HTTP responses. It helps improve performance by storing responses for repeated requests on the client-side, reducing server load and response times. It uses headers for clients to cache the response. cache/README
HTTP Cache The HTTP Cache middleware enables caching of HTTP responses. It's server-side caching mechanism. cache/httpcache/README
HTTP Compression The Compress middleware applies gzip or brotli compression to HTTP responses and client requests decompression. It reduces the size of data transmitted to clients, improving load times and bandwidth utilization. compress/README
CORS The CORS middleware provides Cross-Origin Resource Sharing (CORS) support, allowing your application to handle requests from different origins securely. It sets the appropriate HTTP headers based on your configuration. cors/README
Counter The Counter middleware tracks the number of requests or custom tasks processed by your application. It can be used for monitoring, analytics, or rate-limiting purposes. counter/README
Geolocation The Geolocation middleware enriches incoming requests with geolocation data based on the client's IP address. This can be useful for analytics, content customization, or access control. geolocation/README
gRPC The gRPC middleware integrates gRPC services with your Iris application. It serves gRPC requests alongside ordinary HTTP requests on the same port. grpc/README
hCAPTCHA The hCAPTCHA middleware provides integration with the hCaptcha service, adding CAPTCHA verification to your forms to protect against bots and spam. hcaptcha/README
HTTP Cost The HTTP Cost middleware monitors requests' resource usage (time, memory, CPU) to produce a cost metric for performance analysis or billing. httpcost/README
Localization The Localization middleware serves each client in its own language. It matches the request against the loaded locales through the Accept-Language header, a URL parameter or the subdomain, and exposes the translations to handlers and templates. i18n/README
IP Access Control The IP Access Control middleware decides who reaches your application based on the client's IP address. Allowed and blocked patterns can be exact addresses, CIDR ranges, or regular expressions. ipaccess/README
JWT The JWT middleware handles JSON Web Token (JWT) authentication. It validates the token a client presents and rejects the request when it does not hold up. jwt/README
Method Override The Method Override middleware allows clients to change the HTTP method of a request via a header or form field. This is useful when clients or proxies do not support certain HTTP methods like PUT or DELETE. methodoverride/README
Modrevision The Modrevision middleware embeds versioning information into your application at build time. It helps in tracking and displaying build revisions, useful for debugging and monitoring. modrevision/README
Simple Monitor The Simple Monitor middleware provides basic application health monitoring. It can be used to check the availability and performance of your application endpoints. monitor/README
Profiling The Profiling middleware integrates Go's built-in profiling tool pprof into your application. It assists in performance tuning by providing runtime profiling data. pprof/README
Rate Limit The Rate Limit middleware restricts the number of requests a client can make in a given time period. It helps protect your application against abuse and denial-of-service attacks. rate/README
reCAPTCHA The reCAPTCHA middleware integrates Google's reCAPTCHA service into your forms. It helps prevent spam and automated abuse by verifying that a user is human. recaptcha/README
Request & Response Recorder The Request & Response Recorder middleware captures and records HTTP requests and responses. It is useful for debugging, logging, or replaying requests. recorder/README
Panic Recovery The Panic Recovery middleware recovers from panics that occur during request handling, preventing the application from crashing. It sends a configurable HTTP response or executes a custom recovery function. recovery/README
Referrer The Referrer middleware provides utilities for parsing and validating the HTTP Referer header. It can be used for analytics or security measures like CSRF protection. referrer/README
Request ID The Request ID middleware assigns a unique identifier to each incoming HTTP request. This is useful for tracing requests in logs and debugging. requestid/README
URL Rewrite The Rewrite middleware modifies incoming request URLs based on defined rules. It enables URL rewriting, redirection, or proxying without changing application logic. rewrite/README
Server Timing The Server Timing middleware adds server timing metrics to HTTP responses using the Server-Timing header. This helps in measuring and communicating backend performance to clients. servertiming/README
Sessions The Sessions middleware provides session management using cookies and server-side storage. It keeps user data across requests, with signed and encrypted cookies by default. sessions/README
API Versioning The API Versioning middleware runs several versions of your API side by side. It routes requests to the appropriate handlers based on versioning strategies like URL prefixes or headers. versioning/README
View The View middleware integrates template rendering engines into your application. It supports layouts, partials, and dynamic data binding for server-side rendered pages. view/README
WebSocket The WebSocket middleware provides real-time, bidirectional communication between clients and the server using the WebSocket protocol. It enables the development of interactive applications like chat systems, live feeds, and multiplayer games. websocket/README

Community made

Most of the experimental handlers are ported to work with iris's handler form, from third-party sources.

Middleware Description Example
pg Middleware that provides easy and type-safe access to PostgreSQL database iris-contrib/middleware/pg/_examples
jwt Middleware checks for a JWT on the Authorization header on incoming requests and decodes it iris-contrib/middleware/jwt/_example
cors HTTP Access Control iris-contrib/middleware/cors/_example
secure Middleware that implements a few quick security wins iris-contrib/middleware/secure/_example
tollbooth Generic middleware to rate-limit HTTP requests iris-contrib/middleware/tollboothic/_examples/limit-handler
cloudwatch AWS cloudwatch metrics middleware iris-contrib/middleware/cloudwatch/_example
new relic Official New Relic Go Agent iris-contrib/middleware/newrelic/_example
prometheus Easily create metrics endpoint for the prometheus instrumentation tool iris-contrib/middleware/prometheus/_example
casbin An authorization library that supports access control models like ACL, RBAC, ABAC iris-contrib/middleware/casbin/_examples
sentry-go (ex. raven) Sentry client in Go sentry-go/example/iris
csrf Cross-Site Request Forgery Protection iris-contrib/middleware/csrf/_example
throttler Rate limiting access to HTTP endpoints iris-contrib/middleware/throttler/_example

Third-Party Handlers

Iris has its own middleware form of func(ctx iris.Context) but it's also compatible with all net/http middleware forms. See here.

Here's a small list of useful third-party handlers:

Middleware Description
goth OAuth, OAuth2 authentication.
permissions2 Cookies, users and permissions.
csp Content Security Policy (CSP) support
delay Add delays/latency to endpoints. Useful when testing effects of high latency
onthefly Generate TinySVG, HTML and CSS on the fly
RestGate Secure authentication for REST API endpoints
stats Store information about your web application (response time, etc.)
VanGoH Configurable AWS-Style HMAC authentication middleware
digits Middleware that handles Twitter Digits authentication

Add your own middleware to this list with a pull request.

Directories

Path Synopsis
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.
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.
Package basicauth implements HTTP Basic Authentication (RFC 7617).
Package basicauth implements HTTP Basic Authentication (RFC 7617).
Package bodylimit caps the size of a request body.
Package bodylimit caps the size of a request body.
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.
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.
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.
Package cors implements Cross-Origin Resource Sharing.
Package cors implements Cross-Origin Resource Sharing.
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.
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).
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.
Package hcaptcha verifies the hCaptcha answer that a form submission carries.
Package hcaptcha verifies the hCaptcha answer that a form submission carries.
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.
Package i18n provides internalization and localization features for Iris.
Package i18n provides internalization and localization features for Iris.
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.
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.
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.
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.
Package pprof provides native pprof support via middleware.
Package pprof provides native pprof support via middleware.
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.
Package recaptcha verifies the Google reCAPTCHA answer that a form submission carries.
Package recaptcha verifies the Google reCAPTCHA answer that a form submission carries.
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.
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.
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.
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.
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".
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.
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.
_example command
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.
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.
Package websocket bridges the neffos websocket server with Iris.
Package websocket bridges the neffos websocket server with Iris.

Jump to

Keyboard shortcuts

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