Middleware is a mechanism that allows code to run before or after the main handling code in the lifecycle of an HTTP request. It can be understood as a hook in the framework intercepting all requests and responses.
Using Middleware in iris
You can register middleware to routes through the Use
method in iris.
package main
// Import the package
import "github.com/kataras/iris/v12"
func main() {
// Define the iris instance
app := iris.New()
// Use the gzip compression middleware
app.Use(iris.Compression)
// Route settings
app.Get("/", func(ctx iris.Context) {
ctx.HTML("Hello <strong>%s</strong>!", "World")
})
// Listen on port
app.Listen(":8080")
}
Custom Middleware in iris
// Custom middleware function signature
func Logger() iris.Handler {
// Return the handler through closure
return func(ctx iris.Context) {
t := time.Now()
// Set parameters
ctx.Values().Set("framework", "iris")
// Logic before the request
ctx.Next()
// Logic after the request
latency := time.Since(t)
log.Print(latency)
// Access the status being sent
status := ctx.GetStatusCode()
log.Println(status)
}
}
func main() {
app := iris.New()
// Register the custom middleware
app.Use(Logger())
app.Get("/test", func(ctx iris.Context) {
// Read the parameter set by the middleware
framework := ctx.Values().GetString("framework")
// It would print: "iris"
log.Println(framework)
})
app.Listen(":8080")
}