This repository was archived by the owner on May 11, 2026. It is now read-only.
forked from jooby-project/jooby
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCoroutineRouter.kt
More file actions
79 lines (66 loc) · 2.4 KB
/
Copy pathCoroutineRouter.kt
File metadata and controls
79 lines (66 loc) · 2.4 KB
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
/**
* Jooby https://jooby.io
* Apache License Version 2.0 https://jooby.io/LICENSE.txt
* Copyright 2014 Edgar Espina
*/
package io.jooby
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.launch
import kotlin.coroutines.CoroutineContext
internal class RouterCoroutineScope(coroutineContext: CoroutineContext) : CoroutineScope {
override val coroutineContext = coroutineContext
}
class CoroutineRouter(val coroutineStart: CoroutineStart, val router: Router) {
val coroutineScope: CoroutineScope by lazy {
RouterCoroutineScope(router.worker.asCoroutineDispatcher())
}
@RouterDsl
fun get(pattern: String = "/", handler: suspend HandlerContext.() -> Any): Route {
return route(Router.GET, pattern, handler)
}
@RouterDsl
fun post(pattern: String = "/", handler: suspend HandlerContext.() -> Any): Route {
return route(Router.POST, pattern, handler)
}
@RouterDsl
fun put(pattern: String = "/", handler: suspend HandlerContext.() -> Any): Route {
return route(Router.PUT, pattern, handler)
}
@RouterDsl
fun delete(pattern: String = "/", handler: suspend HandlerContext.() -> Any): Route {
return route(Router.DELETE, pattern, handler)
}
@RouterDsl
fun patch(pattern: String = "/", handler: suspend HandlerContext.() -> Any): Route {
return route(Router.PATCH, pattern, handler)
}
@RouterDsl
fun head(pattern: String = "/", handler: suspend HandlerContext.() -> Any): Route {
return route(Router.HEAD, pattern, handler)
}
@RouterDsl
fun trace(pattern: String = "/", handler: suspend HandlerContext.() -> Any): Route {
return route(Router.TRACE, pattern, handler)
}
@RouterDsl
fun options(pattern: String = "/", handler: suspend HandlerContext.() -> Any): Route {
return route(Router.OPTIONS, pattern, handler)
}
fun route(method: String, pattern: String, handler: suspend HandlerContext.() -> Any): Route {
return router.route(method, pattern) { ctx ->
val xhandler = CoroutineExceptionHandler { _, x ->
ctx.sendError(x)
}
coroutineScope.launch(xhandler, coroutineStart) {
val result = handler(HandlerContext(ctx))
if (result != ctx) {
ctx.render(result)
}
}
}.setHandle(handler)
}
}