dave
06/04/2018, 1:59 PMinternal class ResourceLoadingHandler(private val pathSegments: String,
private val resourceLoader: ResourceLoader,
extraPairs: Map<String, ContentType>) : HttpHandler {
private val extMap = MimeTypes(extraPairs)
override fun invoke(p1: Request): Response = if (p1.uri.path.startsWith(pathSegments)) {
val path = convertPath(p1.uri.path)
resourceLoader.load(path)?.let { url ->
val lookupType = extMap.forFile(path)
if (p1.method == GET && lookupType != OCTET_STREAM) {
Response(OK)
.header("Content-Type", lookupType.value)
.body(Body(ByteBuffer.wrap(url.openStream().readBytes())))
} else Response(NOT_FOUND)
} ?: Response(NOT_FOUND)
} else Response(NOT_FOUND)
private fun convertPath(path: String): String {
val newPath = if (pathSegments == "/" || pathSegments == "") path else path.replace(pathSegments, "")
val resolved = if (newPath == "/" || newPath.isBlank()) "/index.html" else newPath
return resolved.replaceFirst("/", "")
}
}