HttpStatus.kt

  1. package com.hexagonkt.http.model

  2. import com.hexagonkt.core.assertEnabled
  3. import com.hexagonkt.http.model.HttpStatusType.*
  4. import kotlin.IllegalArgumentException

  5. data class HttpStatus(
  6.     val code: Int,
  7.     val type: HttpStatusType = when (code) {
  8.         in 100..199 -> INFORMATION
  9.         in 200..299 -> SUCCESS
  10.         in 300..399 -> REDIRECTION
  11.         in 400..499 -> CLIENT_ERROR
  12.         in 500..599 -> SERVER_ERROR
  13.         else -> throw IllegalArgumentException(INVALID_CODE_ERROR_MESSAGE + code)
  14.     }
  15. ) {
  16.     companion object {
  17.         internal const val INVALID_CODE_ERROR_MESSAGE: String =
  18.             "Error code is not in any HTTP status range (100..599): "

  19.         val codes: Map<Int, HttpStatus> by lazy {
  20.             HTTP_STATUSES.associateBy { it.code }
  21.         }

  22.         operator fun get(code: Int): HttpStatus? =
  23.             codes[code]
  24.     }

  25.     init {
  26.         if (assertEnabled)
  27.             require(code in 100..599) { INVALID_CODE_ERROR_MESSAGE + code }
  28.     }
  29. }