Register Dependency from Context
When you want to create a middleware of iris.Handler form but you want to bind any input arguments of a potential (MVC) Controller's method or dependency-injection handlers.
The ctx.RegisterDependency is the method that allows you to build and add request-time dependencies.
1
// RegisterDependency registers a struct or slice
2
// or pointer to struct dependency at request-time
3
// for the next handler in the chain. One value per type.
4
// Note that it's highly recommended to register
5
// your dependencies before server ran
6
// through Party.ConfigureContainer or mvc.Application.Register
7
// in sake of minimum performance cost.
8
RegisterDependency(v interface{})
9
// UnregisterDependency removes a dependency based on its type.
10
// Reports whether a dependency with that type was
11
// found and removed successfully.
12
UnregisterDependency(typ reflect.Type) bool
Copied!
Let's start by creating a custom middleware that we can use in our hypothetical app.
1
// Role struct value example.
2
type Role struct {
3
Name string
4
}
5
6
const roleContextKey = "myapp.role"
7
8
// RoleMiddleware example of a custom middleware.
9
func RoleMiddleware(ctx iris.Context) {
10
// [do it yourself: extract the role from the request...]
11
if ctx.URLParam("name") != "kataras" {
12
ctx.StopWithStatus(iris.StatusUnauthorized)
13
return
14
}
15
//
16
17
role := Role{Name: "admin"}
18
19
// Share the role value to the next handler(s).
20
ctx.Values().Set(roleContextKey, role)
Copied!
When you have access to the middleware itself: Use the RegisterDependency to register struct type values as dependencies at request-time for any potential dependency injection-ed user handler. This way the user of your middleware can get rid of manually register a dependency for that Role type with calls of APIContainer.RegisterDependency (and mvc.Application.Register).
1
ctx.RegisterDependency(role)
Copied!
1
ctx.Next()
2
}
Copied!
1
// GetRole returns the role inside the context values,
2
// the `roleMiddleware` should be executed first.
3
func GetRole(ctx iris.Context) (Role, bool) {
4
v := ctx.Values().Get(roleContextKey)
5
if v != nil {
6
if role, ok := v.(Role); ok {
7
return role, true
8
}
9
}
10
11
return Role{}, false
12
}
Copied!
It's time to use our RoleMiddleware, in a common iris.Handler and a handler which accepts one or more dependencies. Create a main.go file and copy-paste the following code:
1
package main
2
3
import "github.com/kataras/iris/v12"
4
5
func main() {
6
app := iris.New()
7
app.Use(RoleMiddleware)
8
9
app.Get("/", commonHandler)
10
c := app.ConfigureContainer()
Copied!
When you do NOT have access to the middleware code itself then you can register a request dependency which retrieves the value from the Context and returns it, so handler/function's input arguments with that Role type can be binded.
1
c.RegisterDependency(func(ctx iris.Context) Role {
2
role, ok := GetRole(ctx)
3
if !ok {
4
// This codeblock will never be executed here
5
// but you can stop executing a handler which depends on
6
// that dependency with
7
// `ctx.StopExecution/ctx.StopWithXXX` methods
8
// or by returning a second output argument of `error` type.
9
ctx.StopExecution()
10
return Role{}
11
}
12
13
return role
14
})
Copied!
1
c.Get("/dep", handlerWithDependencies)
2
3
// http://localhost:8080?name=kataras
4
// http://localhost:8080/dep?name=kataras
5
app.Listen(":8080")
6
}
7
8
func commonHandler(ctx iris.Context) {
9
role, _ := GetRole(ctx)
10
ctx.WriteString(role.Name)
11
}
12
13
func handlerWithDependencies(role Role) string {
14
return role.Name
15
}
Copied!
That's all.
Last modified 1yr ago
Export as PDF
Copy link