simple page dispatcher
continuous-integration/drone/push Build is failing
Details
continuous-integration/drone/push Build is failing
Details
parent
c9f45d1bf4
commit
b22a1230c7
@ -0,0 +1,53 @@
|
||||
package org.tbasket.dispatch
|
||||
|
||||
import zio.*
|
||||
import zio.http.*
|
||||
import zio.http.model.Status
|
||||
import zio.http.model.Status.*
|
||||
import zio.stream.ZStream
|
||||
|
||||
import java.nio.file.{Files, Path}
|
||||
import scala.collection.mutable
|
||||
|
||||
class PageDispatcher(pagesLocation: Path) {
|
||||
|
||||
private val resources = resolveResources
|
||||
|
||||
|
||||
def send(r: Request) =
|
||||
ZIO.attempt(pagesLocation.toString + r.url.path.toString)
|
||||
.filterOrFail(!_.startsWith("/"))(Forbidden)
|
||||
.map(resources.get)
|
||||
.someOrFail(NotFound)
|
||||
.map(content => Response(status = Ok, body = content))
|
||||
.catchSome {
|
||||
case status: Status =>
|
||||
ZIO.attempt(Response.status(status))
|
||||
}
|
||||
|
||||
|
||||
private def resolveResources: Map[String, Body] = {
|
||||
|
||||
val map = mutable.HashMap.empty[String, Body]
|
||||
|
||||
def resolveAll(loc: Path): Unit = {
|
||||
Files.list(loc)
|
||||
.forEach {
|
||||
case d if Files.isDirectory(d) => resolveAll(d)
|
||||
case f =>
|
||||
val body = Body.fromStream(ZStream.fromPath(f))
|
||||
val fileName = f.toString
|
||||
map.put(fileName, body)
|
||||
val extension = fileName.drop(fileName.indexOf('.'))
|
||||
|
||||
val dirPath = f.getParent.toString
|
||||
if (extension == ".html")
|
||||
map.put(dirPath, body) //also bind the dir path with the index body
|
||||
else map.put(dirPath + extension, body)
|
||||
}
|
||||
}
|
||||
|
||||
resolveAll(pagesLocation)
|
||||
map.toMap
|
||||
}
|
||||
}
|
Reference in new issue