HttpHandler.kt

  1. package com.hexagonkt.http.handlers

  2. import com.hexagonkt.handlers.Handler
  3. import com.hexagonkt.http.model.*
  4. import com.hexagonkt.http.model.HttpCall

  5. interface HttpHandler : Handler<HttpCall> {
  6.     val handlerPredicate: HttpPredicate

  7.     fun addPrefix(prefix: String): HttpHandler

  8.     fun byMethod(): Map<HttpMethod, HttpHandler> =
  9.         handlerPredicate.methods.associateWith { filter(it) }

  10.     fun filter(method: HttpMethod): HttpHandler =
  11.         when (this) {
  12.             is PathHandler ->
  13.                 copy(
  14.                     handlerPredicate = handlerPredicate.clearMethods(),
  15.                     handlers = handlers
  16.                         .filter {
  17.                             val methods = it.handlerPredicate.methods
  18.                             method in methods || methods.isEmpty()
  19.                         }
  20.                         .map { it.filter(method) }
  21.                 )

  22.             is OnHandler ->
  23.                 copy(handlerPredicate = handlerPredicate.clearMethods())

  24.             is FilterHandler ->
  25.                 copy(handlerPredicate = handlerPredicate.clearMethods())

  26.             is AfterHandler ->
  27.                 copy(handlerPredicate = handlerPredicate.clearMethods())

  28.             is BeforeHandler ->
  29.                 copy(handlerPredicate = handlerPredicate.clearMethods())

  30.             else ->
  31.                 this
  32.         }

  33.     fun processHttp(context: HttpContext): HttpContext =
  34.         if (handlerPredicate(context)) process(context) as HttpContext
  35.         else context

  36.     fun process(request: HttpRequestPort): HttpContext =
  37.         processHttp(HttpContext(HttpCall(request = request), handlerPredicate))
  38. }