Packages

  • package root

    Provided herein is API documentation for Scamper, the HTTP library for Scala.

    Provided herein is API documentation for Scamper, the HTTP library for Scala.

    Definition Classes
    root
  • package scamper

    Defines core types.

    Defines core types.

    HTTP Messages

    At the core of Scamper is HttpMessage, which is a trait that defines the fundamental characteristics of an HTTP message. HttpRequest and HttpResponse extend the specification to define characteristics specific to their respective message types.

    An HttpRequest is created using a factory method defined in its companion object. Or you can start with a RequestMethod and use builder methods to further define the request.

    import scamper.Header
    import scamper.Implicits.stringToUri
    import scamper.RequestMethod.Registry.Get
    
    val request = Get("/motd").setHeaders(
      Header("Host: localhost:8080"),
      Header("Accept: text/plain")
    )
    
    printf("Request Method: %s%n", request.method)
    printf("Target URI: %s%n", request.target)
    
    request.headers.foreach(println)
    
    val host: Option[String] = request.getHeaderValue("Host")

    An HttpResponse is created using a factory method defined in its companion object. Or you can start with a ResponseStatus and use builder methods to further define the response.

    import scamper.{ BodyParser, Header }
    import scamper.Implicits.stringToEntity
    import scamper.ResponseStatus.Registry.Ok
    
    val response = Ok("There is an answer.").setHeaders(
      Header("Content-Type: text/plain"),
      Header("Connection: close")
    )
    
    printf("Status Code: %s%n", response.statusCode)
    printf("Reason Phrase: %s%n", response.reasonPhrase)
    
    response.headers.foreach(println)
    
    val contentType: Option[String] = response.getHeaderValue("Content-Type")
    
    implicit val parser = BodyParser.text()
    
    printf("Body: %s%n", response.as[String])
    Definition Classes
    root
  • package server

    Provides HTTP server implementation.

    Provides HTTP server implementation.

    Building HTTP Server

    To build a server, you begin with ServerApplication. This is a mutable structure to which you apply changes to configure the server. Once the desired settings are applied, you invoke one of several methods to create the server.

    import java.io.File
    import scamper.BodyParser
    import scamper.Implicits.stringToEntity
    import scamper.ResponseStatus.Registry.{ NotFound, Ok }
    import scamper.server.HttpServer
    import scamper.server.Implicits._
    
    // Get server application
    val app = HttpServer.app()
    
    // Add request handler to log all requests
    app.incoming { req =>
      println(req.startLine)
      req
    }
    
    // Add request handler to specific request method and path
    app.get("/about") { req =>
      Ok("This server is powered by Scamper.")
    }
    
    // Add request handler using path parameter
    app.put("/data/:id") { req =>
      def update(id: Int, data: String): Boolean = ???
    
      implicit val parser = BodyParser.text()
    
      // Get path parameter
      val id = req.params.getInt("id")
    
      update(id, req.as[String]) match {
        case true  => Ok()
        case false => NotFound()
      }
    }
    
    // Serve static files
    app.files("/main", new File("/path/to/public"))
    
    // Gzip response body if not empty
    app.outgoing { res =>
      res.body.isKnownEmpty match {
        case true  => res
        case false => res.setGzipContentEncoding()
      }
    }
    
    // Create server
    val server = app.create(8080)
    
    printf("Host: %s%n", server.host)
    printf("Port: %d%n", server.port)
    
    // Run server for 60 seconds
    Thread.sleep(60 * 1000)
    
    // Close server when done
    server.close()
    Definition Classes
    scamper
  • ErrorHandler
  • HttpServer
  • Implicits
  • ParameterNotConvertible
  • ParameterNotFound
  • PathParameters
  • RequestHandler
  • ResponseAborted
  • ResponseFilter
  • Router
  • ServerApplication
  • WebSocketUpgrade

trait Router extends AnyRef

Used for routing request handlers.

import scamper.Implicits.stringToEntity
import scamper.ResponseStatus.Registry.{ NotFound, Ok }
import scamper.server.HttpServer
import scamper.server.Implicits.ServerHttpRequestType

val app = HttpServer.app()

// Mount router to /api
app.route("/api") { router =>
  val messages = Map(1 -> "Hello, world!", 2 -> "Goodbye, cruel world!")

  // Map handler to /api/messages
  router.get("/messages") { req =>
    Ok(messages.mkString("\r\n"))
  }

  // Map handler to /api/messages/:id
  router.get("/messages/:id") { req =>
    val id = req.params.getInt("id")
    messages.get(id)
     .map(Ok(_))
     .getOrElse(NotFound())
  }
}
See also

ServerApplication.route

Linear Supertypes
AnyRef, Any
Known Subclasses
Ordering
  1. Alphabetic
  2. By Inheritance
Inherited
  1. Router
  2. AnyRef
  3. Any
  1. Hide All
  2. Show All
Visibility
  1. Public
  2. All

Abstract Value Members

  1. abstract def incoming(path: String, methods: RequestMethod*)(handler: RequestHandler): Router.this.type

    Adds supplied handler for requests with given router path and any of specified request methods.

    Adds supplied handler for requests with given router path and any of specified request methods.

    The handler is appended to existing request handler chain.

    path

    router path

    methods

    request methods

    handler

    request handler

    returns

    this router

    Note

    If no request methods are specified, then matches are limited to path only.

  2. abstract def incoming(handler: RequestHandler): Router.this.type

    Adds supplied request handler.

    Adds supplied request handler.

    The handler is appended to existing request handler chain.

    handler

    request handler

    returns

    this router

  3. abstract def mountPath: String

    Gets mount path.

Concrete Value Members

  1. final def !=(arg0: Any): Boolean
    Definition Classes
    AnyRef → Any
  2. final def ##(): Int
    Definition Classes
    AnyRef → Any
  3. final def ==(arg0: Any): Boolean
    Definition Classes
    AnyRef → Any
  4. final def asInstanceOf[T0]: T0
    Definition Classes
    Any
  5. def clone(): AnyRef
    Attributes
    protected[lang]
    Definition Classes
    AnyRef
    Annotations
    @throws( ... ) @native()
  6. def delete(path: String)(handler: RequestHandler): Router.this.type

    Adds supplied handler for DELETE requests to given router path.

    Adds supplied handler for DELETE requests to given router path.

    The handler is appended to existing request handler chain.

    path

    router path

    handler

    request handler

    returns

    this router

  7. final def eq(arg0: AnyRef): Boolean
    Definition Classes
    AnyRef
  8. def equals(arg0: Any): Boolean
    Definition Classes
    AnyRef → Any
  9. def files(path: String, source: File): Router.this.type

    Mounts file server at given path.

    Mounts file server at given path.

    At request time, the mount path is stripped from the router path, and the remaining path is used to locate a file in the source directory or one of its subdirectories.

    File Mapping Examples

    Mount Path

    Source Directory

    Router Path

    Maps to

    /images

    /tmp

    /images/logo.png

    /tmp/logo.png

    /images

    /tmp

    /images/icons/warning.png

    /tmp/icons/warning.png

    path

    router path at which directory is mounted

    source

    base directory from which files are served

    returns

    this router

  10. def finalize(): Unit
    Attributes
    protected[lang]
    Definition Classes
    AnyRef
    Annotations
    @throws( classOf[java.lang.Throwable] )
  11. def get(path: String)(handler: RequestHandler): Router.this.type

    Adds supplied handler for GET requests to given router path.

    Adds supplied handler for GET requests to given router path.

    The handler is appended to existing request handler chain.

    path

    router path

    handler

    request handler

    returns

    this router

  12. final def getClass(): Class[_]
    Definition Classes
    AnyRef → Any
    Annotations
    @native()
  13. def hashCode(): Int
    Definition Classes
    AnyRef → Any
    Annotations
    @native()
  14. final def isInstanceOf[T0]: Boolean
    Definition Classes
    Any
  15. final def ne(arg0: AnyRef): Boolean
    Definition Classes
    AnyRef
  16. final def notify(): Unit
    Definition Classes
    AnyRef
    Annotations
    @native()
  17. final def notifyAll(): Unit
    Definition Classes
    AnyRef
    Annotations
    @native()
  18. def post(path: String)(handler: RequestHandler): Router.this.type

    Adds supplied handler for POST requests to given router path.

    Adds supplied handler for POST requests to given router path.

    The handler is appended to existing request handler chain.

    path

    router path

    handler

    request handler

    returns

    this router

  19. def put(path: String)(handler: RequestHandler): Router.this.type

    Adds supplied handler for PUT requests to given router path.

    Adds supplied handler for PUT requests to given router path.

    The handler is appended to existing request handler chain.

    path

    router path

    handler

    request handler

    returns

    this router

  20. def resources(path: String, source: String, loader: ClassLoader): Router.this.type

    Mounts file server (for resources) at given path.

    Mounts file server (for resources) at given path.

    At request time, the mount path is stripped from the router path, and the remaining path is used to locate a resource in the source directory or one of its subdirectories.

    Resource Mapping Examples

    Mount Path

    Source Directory

    Router Path

    Maps to

    /images

    assets

    /images/logo.png

    assets/logo.png

    /images

    assets

    /images/icons/warning.png

    assets/icons/warning.png

    path

    router path at which directory is mounted

    source

    base directory from which resources are served

    loader

    class loader with which resources are loaded

    returns

    this router

  21. def resources(path: String, source: String): Router.this.type

    Mounts file server (for resources) at given path.

    Mounts file server (for resources) at given path.

    At request time, the mount path is stripped from the router path, and the remaining path is used to locate a resource in the source directory or one of its subdirectories.

    Resource Mapping Examples

    Mount Path

    Source Directory

    Router Path

    Maps to

    /images

    assets

    /images/logo.png

    assets/logo.png

    /images

    assets

    /images/icons/warning.png

    assets/icons/warning.png

    path

    router path at which directory is mounted

    source

    base directory from which resources are served

    returns

    this router

    Note

    The current thread's context class loader is used to load resources.

  22. def route[T](path: String)(routing: (Router) ⇒ T): Router.this.type

    Adds new router at given path.

    Adds new router at given path.

    A new router is created and passed to routing application.

    path

    router path at which new router is mounted

    routing

    routing application

    returns

    this router

  23. final def synchronized[T0](arg0: ⇒ T0): T0
    Definition Classes
    AnyRef
  24. def toAbsolutePath(path: String): String

    Expands supplied router path to its absolute path.

    Expands supplied router path to its absolute path.

    path

    router path

    Exceptions thrown

    IllegalArgumentException if router path is not * and does not begin with / or if it escapes mount path

    Note

    If * is supplied as router path, its absolute path is also *.

  25. def toString(): String
    Definition Classes
    AnyRef → Any
  26. final def wait(): Unit
    Definition Classes
    AnyRef
    Annotations
    @throws( ... )
  27. final def wait(arg0: Long, arg1: Int): Unit
    Definition Classes
    AnyRef
    Annotations
    @throws( ... )
  28. final def wait(arg0: Long): Unit
    Definition Classes
    AnyRef
    Annotations
    @throws( ... ) @native()
  29. def websocket[T](path: String)(handler: (WebSocketSession) ⇒ T): Router.this.type

    Adds WebSocket server at given router path using supplied session handler for each connection.

    Adds WebSocket server at given router path using supplied session handler for each connection.

    The handler is appended to existing request handler chain.

    path

    WebSocket path

    handler

    WebSocket session handler

    returns

    this router

Inherited from AnyRef

Inherited from Any

Ungrouped