Middleware
A middleware is a wrapper around a service that provides a means of manipulating
the Request
sent to service, and/or the Response
returned by the service. In
some cases, such as Authentication, middleware may even prevent the service
from being called.
At its most basic, middleware is simply a function that takes one Service
as a
parameter and returns another Service
. In addition to the Service
, the middleware
function can take any additional parameters it needs to perform its task. Let’s look
at a simple example.
For this, we’ll need a dependency on the http4s dsl.
libraryDependencies ++= Seq(
"org.http4s" %% "http4s-dsl" % http4sVersion
)
and some imports.
import cats.effect._
import cats.implicits._
import org.http4s._
import org.http4s.dsl.io._
Then, we can create a middleware that adds a header to successful responses from
the wrapped service like this.
def myMiddle(service: HttpService[IO], header: Header): HttpService[IO] = cats.data.Kleisli { req: Request[IO] =>
service(req).map {
case Status.Successful(resp) =>
resp.putHeaders(header)
case resp =>
resp
}
}
All we do here is pass the request to the service,
which returns an F[Response]
. So, we use map
to get the request out of the task,
add the header if the response is a success, and then pass the response on. We could
just as easily modify the request before we passed it to the service.
Now, let’s create a simple service. As mentioned between service and dsl, because Service
is implemented as a Kleisli
, which is just a function at heart, we can test a
service without a server. Because an HttpService[F]
returns a F[Response[F]]
,
we need to call unsafeRunSync
on the result of the function to extract the Response[F]
.
val service = HttpService[IO] {
case GET -> Root / "bad" =>
BadRequest()
case _ =>
Ok()
}
// service: HttpService[IO] = Kleisli(
// org.http4s.HttpService$$$Lambda$12903/708292025@33a03f08
// )
val goodRequest = Request[IO](Method.GET, uri("/"))
// goodRequest: Request[IO] = Request(
// Method("GET"),
// Uri(None, None, "/", Query(), None),
// HttpVersion(1, 1),
// Headers(),
// Stream(..),
// org.http4s.AttributeMap@8cf85da
// )
val badRequest = Request[IO](Method.GET, uri("/bad"))
// badRequest: Request[IO] = Request(
// Method("GET"),
// Uri(None, None, "/bad", Query(), None),
// HttpVersion(1, 1),
// Headers(),
// Stream(..),
// org.http4s.AttributeMap@8cf85da
// )
service.orNotFound(goodRequest).unsafeRunSync
// res0: Response[IO] = Response(
// Status(200),
// HttpVersion(1, 1),
// Headers(Content-Length(0L)),
// Stream(..),
// org.http4s.AttributeMap@8cf85da
// )
service.orNotFound(badRequest).unsafeRunSync
// res1: Response[IO] = Response(
// Status(400),
// HttpVersion(1, 1),
// Headers(Content-Length(0L)),
// Stream(..),
// org.http4s.AttributeMap@8cf85da
// )
Now, we’ll wrap the service in our middleware to create a new service, and try it out.
val wrappedService = myMiddle(service, Header("SomeKey", "SomeValue"));
// wrappedService: HttpService[IO] = Kleisli(<function1>);
wrappedService.orNotFound(goodRequest).unsafeRunSync
// res2: Response[IO] = Response(
// Status(200),
// HttpVersion(1, 1),
// Headers(Content-Length(0L), Raw(SomeKey, "SomeValue")),
// Stream(..),
// org.http4s.AttributeMap@8cf85da
// )
wrappedService.orNotFound(badRequest).unsafeRunSync
// res3: Response[IO] = Response(
// Status(400),
// HttpVersion(1, 1),
// Headers(Content-Length(0L)),
// Stream(..),
// org.http4s.AttributeMap@8cf85da
// )
Note that the successful response has your header added to it.
If you intend to use you middleware in multiple places, you may want to implement
it as an object
and use the apply
method.
object MyMiddle {
def addHeader(resp: Response[IO], header: Header) =
resp match {
case Status.Successful(resp) => resp.putHeaders(header)
case resp => resp
}
def apply(service: HttpService[IO], header: Header) =
service.map(addHeader(_, header))
}
val newService = MyMiddle(service, Header("SomeKey", "SomeValue"))
// newService: cats.data.Kleisli[cats.data.OptionT[IO, β$0$], Request[IO], Response[IO]] = Kleisli(
// cats.data.Kleisli$$Lambda$13402/1572591205@1a219ed5
// )
newService.orNotFound(goodRequest).unsafeRunSync
// res4: Response[IO] = Response(
// Status(200),
// HttpVersion(1, 1),
// Headers(Content-Length(0L), Raw(SomeKey, "SomeValue")),
// Stream(..),
// org.http4s.AttributeMap@8cf85da
// )
newService.orNotFound(badRequest).unsafeRunSync
// res5: Response[IO] = Response(
// Status(400),
// HttpVersion(1, 1),
// Headers(Content-Length(0L)),
// Stream(..),
// org.http4s.AttributeMap@8cf85da
// )
It is possible for the wrapped Service
to have different Request
and Response
types than the middleware. Authentication is, again, a good example. Authentication
middleware is an HttpService
(an alias for Service[Request, Response]
) that wraps an
AuthedService
(an alias for Service[AuthedRequest[T], Response]
. There is a type
defined for this in the http4s.server
package:
type AuthMiddleware[F, T] = Middleware[AuthedRequest[F, T], Response[F], Request[F], Response[F]]
See the Authentication documentation for more details.
Composing Services with Middleware
Because middleware returns a Service
, you can compose services wrapped in
middleware with other, unwrapped, services, or services wrapped in other middleware.
You can also wrap a single service in multiple layers of middleware. For example:
val apiService = HttpService[IO] {
case GET -> Root / "api" =>
Ok()
}
// apiService: HttpService[IO] = Kleisli(
// org.http4s.HttpService$$$Lambda$12903/708292025@57b0de03
// )
val aggregateService = apiService <+> MyMiddle(service, Header("SomeKey", "SomeValue"))
// aggregateService: cats.data.Kleisli[cats.data.OptionT[IO, β$0$], Request[IO], Response[IO]] = Kleisli(
// cats.data.KleisliSemigroupK$$Lambda$13121/321085675@54bb326e
// )
val apiRequest = Request[IO](Method.GET, uri("/api"))
// apiRequest: Request[IO] = Request(
// Method("GET"),
// Uri(None, None, "/api", Query(), None),
// HttpVersion(1, 1),
// Headers(),
// Stream(..),
// org.http4s.AttributeMap@8cf85da
// )
aggregateService.orNotFound(goodRequest).unsafeRunSync
// res6: Response[IO] = Response(
// Status(200),
// HttpVersion(1, 1),
// Headers(Content-Length(0L), Raw(SomeKey, "SomeValue")),
// Stream(..),
// org.http4s.AttributeMap@8cf85da
// )
aggregateService.orNotFound(apiRequest).unsafeRunSync
// res7: Response[IO] = Response(
// Status(200),
// HttpVersion(1, 1),
// Headers(Content-Length(0L)),
// Stream(..),
// org.http4s.AttributeMap@8cf85da
// )
Note that goodRequest
ran through the MyMiddle
middleware and the Result
had
our header added to it. But, apiRequest
did not go through the middleware and did
not have the header added to it’s Result
.
Included Middleware
Http4s includes some middleware Out of the Box in the org.http4s.server.middleware
package. These include:
And a few others.