Skip to content

Instantly share code, notes, and snippets.

@eungju

eungju/Headers.kt

Last active Jul 21, 2017
Embed
What would you like to do?
HTTP 헤더 이름은 왜 타입을 안만드나?
class Http {
data class HeaderName(val name: String) : Comparable<HeaderName> {
override fun compareTo(other: HeaderName): Int = name.compareTo(other.name, true)
fun get(headers: MultiMap): String? = headers.get(name)
fun set(headers: MultiMap, value: String): Unit { headers.set(name, value) }
fun copyIfExist(from: MultiMap, to: MultiMap) {
get(from)?.let { set(to, it) }
}
}
class Headers {
companion object {
@JvmField
val CONTENT_TYPE = HeaderName("Content-Type")
@JvmField
val HOST = HeaderName("Host")
}
}
}
class ProxyPassHandler(private val config: Config, private val webClient: WebClient) : Handler<RoutingContext> {
data class Config(var upstreamUrl: String) {
constructor() : this("http://upstream")
}
private val logger = LoggerFactory.getLogger(javaClass)
override fun handle(context: RoutingContext) {
val request = context.request()
val response = context.response()
val uri = config.upstreamUrl
logger.debug("Upstream URI {}", uri)
request.bodyHandler()
.flatMap { body ->
webClient.postAbs(uri)
.apply {
Http.Headers.CONTENT_TYPE.copyIfExist(request.headers(), headers())
}
.sendBuffer(body)
}
.map {
logger.debug("Upstream response {}: {}", it.statusCode(), it.bodyAsString())
it.bodyAsJsonObject()
}
.map { ApiResponse.Success(it) }
.subscribe({
response
.putHeader(Http.Headers.CONTENT_TYPE.name, Http.MimeType.JSON)
.end(Json.encodeToBuffer(it))
}, {
context.fail(it)
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment