All Downloads are FREE. Search and download functionalities are using the official Maven repository.

jvmMain.ch.softappeal.yass2.transport.ktor.Http.kt Maven / Gradle / Ivy

There is a newer version: 5.0.0
Show newest version
package ch.softappeal.yass2.transport.ktor

import ch.softappeal.yass2.remote.*
import ch.softappeal.yass2.transport.*
import io.ktor.application.*
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.http.*
import io.ktor.http.content.*
import io.ktor.request.*
import io.ktor.response.*
import io.ktor.routing.*
import kotlinx.coroutines.*
import kotlinx.coroutines.io.*
import kotlin.coroutines.*

private fun write(config: BufferConfig, message: Message) = object : OutgoingContent.WriteChannelContent() {
    override suspend fun writeTo(channel: ByteWriteChannel) = channel.write(config, message)
}

fun httpTunnel(config: BufferConfig, url: String, httpClientFactory: () -> HttpClient): Tunnel = { request ->
    httpClientFactory().use { httpClient ->
        httpClient.call(url) {
            method = HttpMethod.Post
            body = write(config, request)
        }.response.content.read(config) as Reply
    }
}

class CallCce(val call: ApplicationCall) : AbstractCoroutineContextElement(CallCce) {
    companion object Key : CoroutineContext.Key
}

fun Route.route(config: BufferConfig, path: String, tunnel: Tunnel) {
    route(path) {
        post {
            withContext(CallCce(call)) {
                call.respond(write(config, tunnel(call.receiveChannel().read(config) as Request)))
            }
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy