Skip to content

Instantly share code, notes, and snippets.

@soywiz
Created February 12, 2022 07:52
Show Gist options
  • Save soywiz/342e19a38208b16836716bdd56ca423a to your computer and use it in GitHub Desktop.
Save soywiz/342e19a38208b16836716bdd56ca423a to your computer and use it in GitHub Desktop.
Ktor Autoreload Snippet
// implementation("io.methvin:directory-watcher:0.15.0")
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.methvin.watcher.*
import java.io.*
var resourceVersion = 0L
// @TODO: Use websockets instead for instant refresh
fun getAutoreloadScript(): String {
return """
<script>
const resourceVersion = $resourceVersion;
setInterval(async () => {
const newResourceVersion = Number(await (await fetch("/__resourceVersion__")).text())
if (resourceVersion != newResourceVersion) {
document.location.reload();
}
}, 1000);
</script>
""".trimIndent()
}
suspend fun Application.configureAutoreload(folder: File) {
routing {
get("/__resourceVersion__") {
call.respondText("$resourceVersion")
}
}
println("WATCHING...")
resourceVersion = System.currentTimeMillis()
DirectoryWatcher.builder()
.path(folder.toPath())
.listener {
//println(it.eventType())
resourceVersion = System.currentTimeMillis()
}
.build()
.watchAsync()
println("...configured")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment