HttpServerTool.kt

  1. package com.hexagontk.rest.tools

  2. import com.hexagontk.http.handlers.HandlerBuilder
  3. import com.hexagontk.http.model.NOT_FOUND_404
  4. import com.hexagontk.http.server.HttpServer
  5. import com.hexagontk.http.server.HttpServerPort
  6. import com.hexagontk.http.handlers.PathHandler
  7. import com.hexagontk.http.server.HttpServerSettings
  8. import com.hexagontk.rest.SerializeResponseCallback
  9. import java.net.URI

  10. /**
  11.  * Server with dynamic handler (delegated to [path]). Root handler can be replaced at any time
  12.  * without restarting the server.
  13.  */
  14. class HttpServerTool(
  15.     adapter: HttpServerPort,
  16.     settings: HttpServerSettings = HttpServerSettings(),
  17.     var path: PathHandler = PathHandler(),
  18. ) {
  19.     val runtimePort: Int by lazy { server.runtimePort }
  20.     val binding: URI by lazy { server.binding }

  21.     private val server: HttpServer by lazy {
  22.         HttpServer(adapter, settings) {
  23.             // TODO Use SerializeResponseHandler when created
  24.             after("*", SerializeResponseCallback())
  25.             after(pattern = "*", status = NOT_FOUND_404) {
  26.                 send(response = this@HttpServerTool.path.process(request).response)
  27.             }
  28.         }
  29.     }

  30.     fun path(block: HandlerBuilder.() -> Unit) {
  31.         path = com.hexagontk.http.handlers.path(block = block)
  32.     }

  33.     fun start() {
  34.         server.start()
  35.     }

  36.     fun stop() {
  37.         server.stop()
  38.     }
  39. }