Created
July 1, 2020 03:45
-
-
Save Lawliet-L/b7ed6f95e924543a1a29fdc09704476f to your computer and use it in GitHub Desktop.
Demonstration of interceptors and call.attributes for Ktor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun Routing.targetRouting() { | |
data class Target(val name: String) | |
val targetKey = AttributeKey<Target>("TargetKey") | |
suspend fun resolveTarget(target: String): Target? { | |
delay(100) | |
return Target(name = target) | |
} | |
data class Property(val name: String) | |
val propertyKey = AttributeKey<Property>("PropertyKey") | |
suspend fun resolveProperty(property: String): Property? { | |
delay(200) | |
return Property(name = property) | |
} | |
route("{target}") { | |
intercept(ApplicationCallPipeline.Call) { | |
call.parameters["target"]?.let { resolveTarget(it) }?.also { call.attributes.put(targetKey, it) } | |
?: throw Exception("Target cannot be resolved") //will be handled by status pages | |
} | |
route("{property}") { | |
intercept(ApplicationCallPipeline.Call) { | |
call.parameters["property"]?.let { resolveProperty(it) }?.also { call.attributes.put(propertyKey, it) } | |
?: throw Exception("Property cannot be resolved") //will be handled by status pages | |
} | |
get("get") { | |
val resolvedTarget = call.attributes[targetKey].also { println(it) } | |
val resolvedProperty = call.attributes[propertyKey].also { println(it) } | |
//do your stuff | |
call.respondText("Works") | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment