Services

A service receives requests and returns responses. Colossus has built in support for http, memcache, redis and telnet.

Http

A http service will take the following form:

import akka.actor.ActorSystem
import colossus.IOSystem
import colossus.protocols.http.Http
import colossus.protocols.http.HttpMethod._
import colossus.protocols.http.UrlParsing._
import colossus.protocols.http.server.{HttpServer, Initializer, RequestHandler}
import colossus.service.Callback.Implicits._
import colossus.service.GenRequestHandler.PartialHandler

object HttpService extends App {

  implicit val actorSystem = ActorSystem()
  implicit val ioSystem = IOSystem()

  HttpServer.start("example-server", 9000) {
    new Initializer(_) {
      override def onConnect = new RequestHandler(_) {
        override def handle: PartialHandler[Http] = {
          case request @ Get on Root / "hello" =>
            request.ok("Hello world!")
        }
      }
    }
  }
}

ok is a helper method on HttpRequest that returns a HttpResponse. The implicit colossus.service.Callback.Implicits.objectToSuccessfulCallback then turns the response into a Callback[HttpResponse].

The following helper method are available, which will default the content type to text and return the corresponding http code.

  • ok
  • notFound
  • error
  • badRequest
  • unauthorized
  • forbidden

There are several different ways to set headers on the response.

request.ok("hello").withHeader("header-name", "header-value")
request.ok("hello", HttpHeaders(HttpHeader("header-name", "header-value")))
request.ok("hello", HttpHeaders(HttpHeader(HttpHeaders.CookieHeader, "header-value")))

Setting the content type or using a different http code involves a bit more work as the above helper methods can’t be used. Instead use the respond method.

request.respond(HttpCodes.CONFLICT, HttpBody("""{"name":"value"}""").withContentType(ContentType.ApplicationJson))

On the incoming request, body and content type are on the HttpBody and headers and parameters are on the HttpHead.

val body: String = request.body.bytes.utf8String
val contentType: Option[HttpHeader] = request.body.contentType
val headers: HttpHeaders = request.head.headers
val parameter: Option[String] = request.head.parameters.getFirst("key")