/ktor-middleware

Add middlewares to ktor

Primary LanguageKotlin

KTOR Middleware

Adds Laravel inspired Middlewares to KTOR with simple syntax.

Add to your project

implementation("io.github.staticfx:ktor-middleware:v1.1.1")

Simple Middleware

class MyMiddleware: Middleware {
    override suspend fun handleCall(call: ApplicationCall, cancel: (exception: CancellationException?) -> Unit) {
        //your code
    }
}

Middleware groups

val group = middlewareGroup { 
    this += MyMiddleware()
}

Transfer Data

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 = ""
}

Use Middleware for specific routes

Simple:

middleware(MyMiddleware()) {
    get("/") {
    }
}

Groups:

middleware(MyMiddlewareGroup()) {
    get("/") {
    }
}

Global Middleware

install(Middlewares) {
    middleware = MyMiddleware()
}

Or with groups

install(Middlewares) {
    middleware = middlewareGroup {
        this += MyMiddleware()
    }
}

Roadmap

  • Add data object to persist data between middlewares
  • Improve experience of the cancel function
  • Add better builders for middlewares
  • Add sample middlewares