Skip to content

Instantly share code, notes, and snippets.

@hamnis
Last active June 29, 2020 18:58
Show Gist options
  • Save hamnis/b2e3906a1939fc9e1c09a086ce98fc72 to your computer and use it in GitHub Desktop.
Save hamnis/b2e3906a1939fc9e1c09a086ce98fc72 to your computer and use it in GitHub Desktop.
package com.example.http4s
import cats.data.OptionT
import cats.effect.Sync
import org.http4s.dsl.impl.Path
import org.http4s.headers.Allow
import org.http4s.{AuthedRoutes, HttpRoutes, Method, Response, Status}
object Route {
def of[F[_]: Sync](pf: PartialFunction[Path, Map[Method, HttpRoutes[F]]]): HttpRoutes[F] = HttpRoutes[F] { req =>
val path = Path(req.pathInfo)
if (pf.isDefinedAt(path)) {
val methods = pf(path)
val route = methods.getOrElse(
req.method,
HttpRoutes.pure(
Response[F](Status.MethodNotAllowed).putHeaders(Allow(methods.keySet))
)
)
route(req)
} else OptionT.none
}
def apply[F[_]: Sync](path: Path, methods: (Method, HttpRoutes[F])*): HttpRoutes[F] =
of { case `path` => methods.toMap }
}
object AuthedRoute {
def of[A, F[_]: Sync](pf: PartialFunction[Path, Map[Method, AuthedRoutes[A, F]]]): AuthedRoutes[A, F] =
AuthedRoutes[A, F] { authed =>
val path = Path(authed.req.pathInfo)
if (pf.isDefinedAt(path)) {
val methods = pf(path)
val route: AuthedRoutes[A, F] = methods.getOrElse(
authed.req.method,
AuthedRoutes(
_ => OptionT.some[F](Response[F](Status.MethodNotAllowed).putHeaders(Allow(methods.keySet)))
)
)
route(authed)
} else OptionT.none
}
def apply[A, F[_]: Sync](path: Path, methods: (Method, AuthedRoutes[A, F])*): AuthedRoutes[A, F] =
of { case `path` => methods.toMap }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment