Created
August 4, 2019 14:33
-
-
Save markosski/4dd5df07ce331083d963f174c846184a to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import cats.effect.ExitCode | |
import cats.data.{NonEmptyList} | |
import org.http4s.HttpRoutes | |
import org.http4s.dsl.io._ | |
import org.http4s.server.blaze._ | |
import org.http4s.implicits._ | |
import org.http4s.server.Router | |
import org.http4s.Header | |
import org.http4s.StaticFile | |
import org.http4s.headers.{`Cache-Control`, `Content-Type`} | |
import org.http4s.CacheDirective.`no-cache` | |
import org.http4s.dsl.Http4sDsl | |
import zio._ | |
import zio.blocking.Blocking | |
import zio.clock.Clock | |
import zio.console._ | |
import zio.interop.catz._ | |
import zio.interop.catz.implicits._ | |
import scala.concurrent.ExecutionContext | |
import java.util.concurrent._ | |
import java.io.File | |
import java.io.StringWriter | |
import de.zalando.beard.renderer._ | |
object Main extends App { | |
type AppEnvironment = Clock with Console with Blocking | |
type AppTask[A] = TaskR[AppEnvironment, A] | |
val dsl: Http4sDsl[AppTask] = Http4sDsl[AppTask] | |
import dsl._ | |
def routes(ec: ExecutionContext) = HttpRoutes.of[AppTask] { | |
case request @ GET -> Root / "pages" / page => { | |
val fileName = request.pathInfo.split("/").last | |
val contentHeader = if (fileName.endsWith(".png")) { | |
Header("Content-Type", "image/png") | |
} else { | |
Header("Content-Type", "text/html") | |
} | |
StaticFile | |
.fromFile(new File(s"/tmp/webparse/capture/${page}"), ec, Some(request)) | |
.map(_.putHeaders(contentHeader, `Cache-Control`(NonEmptyList.of(`no-cache`())))) | |
.getOrElseF(NotFound()) | |
} | |
}.orNotFound | |
def run(args: List[String]): ZIO[Environment, Nothing, Int] = { | |
for { | |
blockingEC <- ZIO.environment[Blocking].flatMap(_.blocking.blockingExecutor).map(_.asEC) | |
server <- ZIO.runtime[AppEnvironment].flatMap { implicit rts => | |
BlazeServerBuilder[AppTask] | |
.bindHttp(8080, "localhost") | |
.withHttpApp(routes(blockingEC)) | |
.serve | |
.compile[AppTask, AppTask, ExitCode] | |
.drain | |
} | |
} yield server | |
}.foldM(_ => ZIO.succeed(1), _ => ZIO.succeed(0)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment