-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
main.go
95 lines (76 loc) · 2.34 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package main
import "github.com/kataras/iris/v12"
func main() {
app := iris.New()
app.Use(RoleMiddleware)
app.Get("/", commonHandler)
c := app.ConfigureContainer()
/*
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.
c.RegisterDependency(func(ctx iris.Context) Role {
role, ok := GetRole(ctx)
if !ok {
// This codeblock will never be executed here
// but you can stop executing a handler which depends on
// that dependency with `ctx.StopExecution/ctx.StopWithXXX` methods
// or by returning a second output argument of `error` type.
ctx.StopExecution()
return Role{}
}
return role
})
*/
c.Get("/dep", handlerWithDependencies)
// http://localhost:8080?name=kataras
// http://localhost:8080/dep?name=kataras
app.Listen(":8080")
}
func commonHandler(ctx iris.Context) {
role, _ := GetRole(ctx)
ctx.WriteString(role.Name)
}
func handlerWithDependencies(role Role) string {
return role.Name
}
// Code for an example middleware.
// Role struct value example.
type Role struct {
Name string
}
const roleContextKey = "myapp.role"
// RoleMiddleware example of a custom middleware.
func RoleMiddleware(ctx iris.Context) {
// [do it yourself: extract the role from the request...]
if ctx.URLParam("name") != "kataras" {
ctx.StopWithStatus(iris.StatusUnauthorized)
return
}
//
role := Role{Name: "admin"}
ctx.Values().Set(roleContextKey, role)
// 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`).
ctx.RegisterDependency(role)
ctx.Next()
}
// GetRole returns the role inside the context values,
// the `roleMiddleware` should be executed first.
func GetRole(ctx iris.Context) (Role, bool) {
v := ctx.Values().Get(roleContextKey)
if v != nil {
if role, ok := v.(Role); ok {
return role, true
}
}
return Role{}, false
}
// End Code of our example middleware.