Skip to content

Instantly share code, notes, and snippets.

@laithnurie
Last active January 29, 2025 08:41
Show Gist options
  • Save laithnurie/2f4d3ed3f0a8dac053961ce2899f528b to your computer and use it in GitHub Desktop.
Save laithnurie/2f4d3ed3f0a8dac053961ce2899f528b to your computer and use it in GitHub Desktop.
Local ktor server
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