@@ -61,9 +61,10 @@ A javadoc:Route[] consists of three part:
6161The javadoc:Route.Handler[text="handler"] function always produces a result, which is send it back
6262to the client.
6363
64- ==== Route attributes
64+ ==== Attributes
6565
6666Attributes let you annotate a route at application bootstrap time. It functions like static metadata available at runtime:
67+
6768.Java
6869[source, java, role="primary"]
6970----
@@ -72,8 +73,20 @@ Attributes let you annotate a route at application bootstrap time. It functions
7273 .attribute("foo", "bar");
7374}
7475----
76+
77+ .Kotlin
78+ [source, kotlin, role="secondary"]
79+ ----
80+ {
81+ get("/foo") {
82+ "Foo"
83+ }.attribute("foo", "bar")
84+ }
85+ ----
86+
7587An attribute consist of a name and value. Values can be any object.
7688Attributes can be accessed at runtime in a request/response cycle. For example, a security module might check for a role attribute.
89+
7790.Java
7891[source, java, role="primary"]
7992----
@@ -91,7 +104,25 @@ Attributes can be accessed at runtime in a request/response cycle. For example,
91104}
92105----
93106
107+ .Kotlin
108+ [source, kotlin, role="secondary"]
109+ ----
110+ {
111+ decorator(
112+ val user = ...
113+ val role = ctx.route.attribute("Role")
114+
115+ if (user.hasRole(role)) {
116+ return next.apply(ctx)
117+ } else {
118+ throw StatusCodeException(StatusCode.FORBIDDEN)
119+ }
120+ }
121+ ----
122+
123+
94124In MVC routes you can set attributes via annotations:
125+
95126.Java
96127[source, java, role="primary"]
97128----
@@ -113,24 +144,42 @@ public class AdminResource {
113144
114145{
115146 decorator(next -> ctx -> {
116- System.out.println(ctx.getRoute().attribute("Role"))
147+ System.out.println(ctx.getRoute().attribute("Role"));
117148 });
118149}
119150----
151+
152+ .Kotlin
153+ [source, kotlin, role="secondary"]
154+ ----
155+ @Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
156+ @Retention(AnnotationRetention.RUNTIME)
157+ annotation class Role (val value: String)
158+
159+ @Path("/path")
160+ class AdminResource {
161+
162+ @Role("admin")
163+ fun doSomething() : Any {
164+ ...
165+ }
166+
167+ }
168+
169+ {
170+ decorator {
171+ println(ctx.route.attribute("Role"))
172+ }
173+ }
174+ ----
175+
120176The previous example will print: admin.
121177You can retrieve all the attributes of the route by calling `ctx.getRoute().getAttributes()`.
122178
123179Any runtime annotation is automatically added as route attributes following these rules:
124180- If the annotation has a value method, then we use the annotation’s name as the attribute name.
125181- Otherwise, we use the method name as the attribute name.
126182
127- .request attributes vs route attributes
128- [NOTE]
129- ====
130- Route attributes are created at bootstrap. They are global, and once set, they won’t change.
131- On the other hand, request attributes are created in a request/response cycle.
132- ====
133-
134183
135184=== Path Pattern
136185
0 commit comments