mirror of
https://github.com/kataras/iris.git
synced 2025-01-23 18:51:03 +01:00
.. | ||
README.md |
Middleware
We should mention that Iris is compatible with ALL net/http middleware out there, You are not restricted to so-called 'iris-made' middleware. They do exists, mostly, for your learning curve.
Navigate through iris-contrib/middleware repository to view iris-made 'middleware'.
By the word 'middleware', we mean a single or a collection of route handlers which may execute before/or after the main route handler.
Installation
$ go get github.com/iris-contrib/middleware/...
How can I register a middleware?
app := iris.New()
/* per root path and all its children */
app.Use(logger)
/* execute always last */
// app.Done(logger)
/* per-route, order matters. */
// app.Get("/", logger, indexHandler)
/* per party (group of routes) */
// userRoutes := app.Party("/user", logger)
// userRoutes.Post("/login", loginAuthHandler)
How 'hard' is to create an Iris middleware?
myMiddleware := func(ctx *iris.Context){
/* using ctx.Set you can transfer ANY data between handlers,
use ctx.Get("welcomed") to get its value on the next handler(s).
*/
ctx.Set("welcomed", true)
println("My middleware!")
}
func(ctx *iris.Context) is just the
iris.HandlerFunc
signature which implements theiris.Handler
/Serve(Context)
method.
app := iris.New()
/* root path and all its children */
app.UseFunc(myMiddleware)
app.Get("/", indexHandler)
Convert http.Handler
to iris.Handler
using the iris.ToHandler
// ToHandler converts different type styles of handlers that you
// used to use (usually with third-party net/http middleware) to an iris.HandlerFunc.
//
// Supported types:
// - .ToHandler(h http.Handler)
// - .ToHandler(func(w http.ResponseWriter, r *http.Request))
// - .ToHandler(func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc))
func ToHandler(handler interface{}) HandlerFunc
app := iris.New()
sillyHTTPHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
println(r.RequestURI)
})
app.Use(iris.ToHandler(sillyHTTPHandler))
What next?
Read more about iris.Handler, iris.HandlerFunc and Middleware.