Skip to content

Instantly share code, notes, and snippets.

@corlaez
Last active June 6, 2023 03:12
Show Gist options
  • Save corlaez/1a9683534fc131290924ec7fc024d9ab to your computer and use it in GitHub Desktop.
Save corlaez/1a9683534fc131290924ec7fc024d9ab to your computer and use it in GitHub Desktop.
Kotlin Webjars Locator Ktor Gradle

This is how I like to use webjars in kotlin.

build.gradle.kts dependencies:

dependencies {
    // webjars
    implementation("org.webjars:webjars-locator:0.46")
    implementation("org.webjars.npm:htmx.org:1.9.2")
}

endpoint:

val htmx = textFromWebJar("htmx.js")
routing {
  get("/asset/htmx.js") { call.respondText(htmx, ContentType.Application.JavaScript)  }
}
package util
import org.webjars.WebJarAssetLocator
import java.nio.charset.Charset
private val locator by lazy { WebJarAssetLocator() }
// Do not use a trailing / for resource paths
// IMPORTANT: Must use getSystemResourceAsStream to load a resource from a jar
internal fun textFromResource(name: String, charset: Charset = Charset.forName("UTF-8")) =
ClassLoader.getSystemResourceAsStream(name)!!.bufferedReader(charset).readText()
internal fun fullPathForWebjar(trailingPath: String) = locator.getFullPath(trailingPath)
internal fun textFromWebjar(trailingPath: String) = locator
.getFullPath(trailingPath)
.let(::textFromResource)
internal fun textFromWebjar(artifactId: String, trailingPath: String) = locator.allWebJars.values
.first { it.artifactId == artifactId }.contents
.first { it.contains(trailingPath) }
.let(::textFromResource)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment