ContentType.kt

  1. package com.hexagonkt.http.model

  2. import com.hexagonkt.core.media.MediaType
  3. import com.hexagonkt.core.assertEnabled
  4. import java.nio.charset.Charset

  5. data class ContentType(
  6.     val mediaType: MediaType,
  7.     val boundary: String? = null,
  8.     val charset: Charset? = null,
  9.     val q: Double? = null,
  10. ) {

  11.     val text by lazy {
  12.         listOfNotNull(
  13.             mediaType.fullType,
  14.             boundary?.let { "boundary=$it" },
  15.             charset?.let { "charset=$it" },
  16.             q?.let { "q=$it" }
  17.         )
  18.         .joinToString(";")
  19.     }

  20.     init {
  21.         if (assertEnabled) {
  22.             val a = if (boundary == null) 0 else 1
  23.             val b = if (charset == null) 0 else 1
  24.             val c = if (q == null) 0 else 1

  25.             require(a + b + c in 0..1) { "Only one parameter can be set: $this" }
  26.             require(boundary?.isNotBlank() ?: true) { "Boundary can not be blank" }
  27.             require(q?.let { it in 0.0..1.0 } ?: true) { "Q must be in the 0 to 1 range: $q" }
  28.         }
  29.     }
  30. }