concept HttpService in category scala

appears as: An HttpService, n HttpService, HttpService
Get Programming with Scala

This is an excerpt from Manning's book Get Programming with Scala.

Before explaining how to implement an HTTP server using http4s, let me give you an overview of its architecture. First, you need to link your routes to their business logic through instances of org.http4s.HttpService. An HttpService uses partial functions to match an incoming HTTP request, and it produces an HTTP response together with a side effect (e.g., an IO read/write, a connection to a third party). At this point, you may not be familiar with the concept of side effects, but do not worry as you’ll learn what they are in the next unit. Most applications use cats.effect.IO as a generic representation of both synchronous and asynchronous side effects: in lesson 32, you are going to learn about side effects and why their representation is crucial. Finally, you define a singleton object that extends fs2.StreamApp in which you need to provide instructions on the port and host to bind and services to mount. The StreamApp uses Blaze (see https://github.com/http4s/blaze) together with streams as the backend for network IO. Figure 17.1 provides a visual summary of the components of an http4s application.

17.2.2   Implementing an HttpService

Let’s define a class, called PingService, with a value that contains an instance of an HttpService. PingService should extend Http4sDsl, a trait that introduces a more intuitive DSL to match HTTP requests and produce HTTP responses. A possible implementation is the following:

// file src/main/scala/org/example/ping/PingService.scala
 
package org.example.ping
 
import cats.effect.IO
import org.http4s.HttpService
import org.http4s.dsl.Http4sDsl
 
class PingService extends Http4sDsl[IO] { //#A
 
  val service = HttpService[IO] { //#B
    case GET -> Root / "ping" => Ok("pong") //#C //#D
  }
}