Skip to content

Instantly share code, notes, and snippets.

@Vilkina
Created February 11, 2020 07:16
Show Gist options
  • Save Vilkina/f4ba63b92f760d16d12f4ab9a6188906 to your computer and use it in GitHub Desktop.
Save Vilkina/f4ba63b92f760d16d12f4ab9a6188906 to your computer and use it in GitHub Desktop.
package ziolist.http4s
import org.http4s._
import zio._
import zio.interop.catz._
import org.http4s.server.blaze.BlazeServerBuilder
object Service {
//E for Effect
//type E[X] = Task[X]
object http4sZioTaskDsl extends org.http4s.dsl.Http4sDsl[Task]
import http4sZioTaskDsl._
import org.http4s.HttpRoutes
import org.http4s.UrlForm
//OOP : covariance OOP+ : contravariance
import org.http4s.headers._
val helloWorld: HttpRoutes[Task] = HttpRoutes.of[Task] {
case GET -> Root / "hello" / name =>
for {
_ <- Task.effect(println(s"greeting $name"))
response <- Ok(s"Hello, $name.")
} yield response
case GET -> Root => Ok(s"""<!DOCTYPE html>
<html>
Hello World ! What is you name ?
<form action="/greet" method="POST">
<input type="text" name="name" />
<input type="submit" />
</form>
</html>
""").map(_.withContentType(`Content-Type`(MediaType.text.`html`)))
case req @ POST -> Root / "greet" =>
req.decode[UrlForm] { m =>
m.getFirst("name") match {
case Some(name) =>
Uri.fromString(s"/hello/$name") match {
case Right(value) => SeeOther(Location(value))
case _ => ???
}
case None => SeeOther(Location(Uri.uri("/")))
}
}
case req @ POST -> Root / "form-encoded" =>
// EntityDecoders return an F[A] which is easy to sequence
req.decode[UrlForm] { m =>
val s = m.values.mkString("\n")
Ok(s"Form Encoded Data\n$s")
}
}
}
object ServerApp extends CatsApp {
import zio.interop.catz.implicits._
import org.http4s.implicits._
override def run(args: List[String]): URIO[Any, Int] =
BlazeServerBuilder[Task]
// .bindHttp(9090, "localhost")
.withHttpApp(Service.helloWorld.orNotFound)
.serve
.compile
.drain
.as(0)
.orDie
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment