Skip to content

Instantly share code, notes, and snippets.

@yasuabe
Created March 26, 2019 22:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yasuabe/f84cf8e5637bc2df79326299a921b2b7 to your computer and use it in GitHub Desktop.
Save yasuabe/f84cf8e5637bc2df79326299a921b2b7 to your computer and use it in GitHub Desktop.
simple http4s server program for examining Doobie
package withhttp4s
import cats.effect.{IO, IOApp}
import cats.implicits._
import org.http4s.{HttpApp, HttpRoutes}
import org.http4s.implicits._
import org.http4s.server.blaze._
import cats.effect._
import doobie._
import doobie.implicits._
import io.circe.generic.auto._
import io.circe.syntax._
import org.http4s.circe._
import org.http4s.dsl.Http4sDsl
//case class City(id: Int, name: String, district: Double)
case class City(id: Int, name: String, district: String)
class MyService[F[_]: Async: ContextShift] extends Http4sDsl[F] {
def xa: Transactor[F] = Transactor.fromDriverManager[F](
"org.postgresql.Driver", "jdbc:postgresql:world", "postgres", "pass"
)
def findCitiesByCountry(c: String): doobie.Query0[City] =
sql"select id, name, district from city where countrycode = $c".query[City]
object CountryCodeMatcher extends QueryParamDecoderMatcher[String]("countryCode")
def app: HttpApp[F] = HttpRoutes.of[F] {
case GET -> Root / "cities" :? CountryCodeMatcher(code) =>
Ok(findCitiesByCountry(code).stream.map(_.asJson).transact(xa))
}.orNotFound
}
object ServerMain extends IOApp {
def run(args: List[String]): IO[ExitCode] =
BlazeServerBuilder[IO]
.bindHttp(8080, "localhost")
.withHttpApp(new MyService[IO].app)
.serve
.compile.drain
.as(ExitCode.Success)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment