Last active
January 29, 2025 08:41
-
-
Save laithnurie/2f4d3ed3f0a8dac053961ce2899f528b to your computer and use it in GitHub Desktop.
Local ktor server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
io-ktor = "2.3.11" | |
io-ktor-ktor-client-android = { module = "io.ktor:ktor-client-android", version.ref = "io-ktor" } | |
io-ktor-ktor-client-cio = { module = "io.ktor:ktor-client-cio", version.ref = "io-ktor" } | |
io-ktor-ktor-server-cio = { module = "io.ktor:ktor-server-cio", version.ref = "io-ktor" } | |
io-ktor-ktor-server-core = { module = "io.ktor:ktor-server-core", version.ref = "io-ktor" } | |
object LocalServer { | |
private var server: CIOApplicationEngine? = null | |
fun start() { | |
val assets = InstrumentationRegistry.getInstrumentation().context.assets | |
server?.stop() | |
server = embeddedServer(CIO, port = 8080) { | |
routing { | |
get("api/path/here") { | |
call.respondText( | |
text = assets.toJson("json path here"), | |
contentType = ContentType.Application.Json, | |
status = HttpStatusCode.OK | |
) | |
} | |
} | |
server.start() | |
} | |
private fun AssetManager.toJson(fileName: String) = open(fileName).let { | |
JSONObject(it.bufferedReader().readText()).toString() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment