Created
February 12, 2022 07:52
-
-
Save soywiz/342e19a38208b16836716bdd56ca423a to your computer and use it in GitHub Desktop.
Ktor Autoreload Snippet
This file contains 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
// 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