Adds Laravel inspired Middlewares to KTOR with simple syntax.
implementation("io.github.staticfx:ktor-middleware:v1.1.1")
class MyMiddleware: Middleware {
override suspend fun handleCall(call: ApplicationCall, cancel: (exception: CancellationException?) -> Unit) {
//your code
}
}
val group = middlewareGroup {
this += MyMiddleware()
}
class DataPassingMiddleware : Middleware {
override suspend fun handleCall(
call: ApplicationCall,
receives: MiddlewareData?,
): MiddlewareData {
val data = SingleValueMiddlewareData()
data.data = "Test"
return data
}
}
class DataReceivingMiddleware : Middleware {
override suspend fun handleCall(
call: ApplicationCall,
receives: MiddlewareData?,
): MiddlewareData {
if (receives == null) call.cancel()
val data = receives as SingleValueMiddlewareData
call.respondText { data.data }
return MiddlewareData.empty()
}
}
class SingleValueMiddlewareData : MiddlewareData {
var data: String = ""
}
Simple:
middleware(MyMiddleware()) {
get("/") {
}
}
Groups:
middleware(MyMiddlewareGroup()) {
get("/") {
}
}
install(Middlewares) {
middleware = MyMiddleware()
}
Or with groups
install(Middlewares) {
middleware = middlewareGroup {
this += MyMiddleware()
}
}
- Add data object to persist data between middlewares
- Improve experience of the cancel function
- Add better builders for middlewares
- Add sample middlewares