https://kotlinlang.org logo
#ktor
Title
# ktor
c

Carter

12/08/2023, 3:21 PM
A while back I was asking about using asset hashes in filenames to help bust CDN caches. For now, I’m avoiding generating the hashes at build time, instead generating them dynamically at runtime. I prototyped something that works. This works, but uses deprecated
resource
API:
Copy code
Assets.entries.forEach {
    resource(
        it.hashedPath, // asset/js/browser-app-af00f73c8693fe418e83b020c04d3e78324a1e7dc5a0dd3784de87f66d9ebf68.js
        it.defaultPath // asset/js/browser-app.js
    )
}
This does not work, using
staticResources
.
Copy code
Assets.entries.forEach {
    staticResources(
        it.hashedPath, // asset/js/browser-app-af00f73c8693fe418e83b020c04d3e78324a1e7dc5a0dd3784de87f66d9ebf68.js
        it.basePackage // asset/js
    ) {
        default(it.defaultPath) // asset/js/browser-app.js
    }
}
Is there a way to do this better with the
staticResources
or another Ktor API?
a

Aleksei Tirman [JB]

12/08/2023, 4:29 PM
You can replace the deprecated code with the following one:
Copy code
Assets.entries.forEach { entry ->
    get(entry.hashedPath) {
        val resource = call.resolveResource(entry.defaultPath)
        if (resource != null) call.respond(resource)
    }
}
c

Carter

12/08/2023, 7:38 PM
Works like a charm, thank you! Finding
resolveResource
was the challenge!
Is there any existing Ktor issue for generating hashes for assets? If there’s not, I might soon file an issue since my solution works for now but has some limitations that a built-in solution might be able to handle better. At least it could articulate the use case for the team to consider this functionality in the future.
a

Aleksei Tirman [JB]

12/09/2023, 11:54 AM
I cannot find such feature request.
👍 1
c

Carter

01/29/2024, 5:21 PM