Skip to content

HTTP Server

Module http_server

This port's purpose is to develop HTTP servers (REST services or Web applications). It defines a DSL to declare HTTP request handlers.

Adapters implementing this port are in charge of processing HTTP requests through a list of handlers.

Install the Dependency

This module is not meant to be used directly. You should include and Adapter implementing this feature (as http_server_jetty) in order to create an HTTP server.

Context on HTTP processing

An HTTP server is nothing more than a function that takes a request and returns a response. Requests and responses comply with several Web standards.

For the sake of ease of use, HTTP toolkits (or frameworks) are built. These tools make easier to write an HTTP server that has to deal with different behaviour based on requests attributes.

These development tools usually have different layers/parts (the ones below are some of the most common ones):

  • IO: sockets and buffers management, SSL and thread scheduling is usually handled here also.
  • HTTP messages parsing: parse requests to internal model and serialize responses to bytes.
  • Routing: makes easy to run different blocks of code based on requests (usually supporting pipelining among different blocks).

Hexagon takes care of the third layer, it's "just" an abstraction layer for the IO engine and HTTP parser underneath, those two layers depends on the adapter (which you can select from a few alternatives).

This particularity allows users to swap adapters for different use cases. For example, You can use a low memory for embedded boards (as Raspberry Pi) or high through-output for servers, another use case would be to use a fast boot adapter for development, and select a different one for production.

To be agnostic of the adapter below, a custom HTTP model is implemented in Hexagon, and adapters must map their own structures to this model.

Now we'll talk about how HTTP routing is done in the toolkit. The cornerstone of HTTP handling in Hexagon is the handler: Hexagon handlers are a list of functions that may or may not be applied to an HTTP call depending on a predicate.

Handlers have a predicate, and they are only applied to a given request if the current request matches the predicate.

The functions that handle HTTP requests (named 'callbacks' in Hexagon) are blocks of code that get an HTTP call and return an HTTP call (probably the received one with a modified response), callbacks operate on immutable structures (the HTTP model).

Below you can find an in deep description of the concepts and components of this toolkit.

Servers

A server is a process listening to HTTP requests on a TCP port.

You can run multiple ones on different ports at the same time on the same JVM (this can be useful to test many microservices at the same time).

The server can be configured with different properties. If you do not provide a value for them, they are searched inside the application settings and lastly, a default value is picked. This is the parameters list:

  • banner: informative text shown at start up logs. If not set only runtime information is displayed.
  • bindAddress: address to which this process is bound. If none is provided, 127.0.0.1 is taken.
  • bindPort: the port which the process listens to. By default, it is 2010.
  • contextPath: initial path used for the rest of the routes, by default it is empty.

To create a server, you need to provide a handler (check the handlers section for more information), and after creating a server you can run it or stop it with start() and stop() methods.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/*
 * All settings are optional, you can supply any combination
 * Parameters not set will fall back to the defaults
 */
val settings = HttpServerSettings(
    bindAddress = InetAddress.getByName("0.0.0"),
    bindPort = 2020,
    contextPath = "/context",
    banner = "name"
)

val path = path {
    get("/hello") { ok("Hello World!") }
}

val runningServer = serve(serverAdapter(), listOf(path), settings)

// Servers implement closeable, you can use them inside a block assuring they will be closed
runningServer.use { s ->
    HttpClient(clientAdapter(), URL("http://localhost:${s.runtimePort}")).use {
        it.start()
        assert(s.started())
        assertEquals("Hello World!", it.get("/context/hello").body)
    }
}

/*
 * You may skip the settings and the defaults will be used
 */
val defaultSettingsServer = serve(serverAdapter(), listOf(path))

Servlet Web server

There is a special server adapter for running inside Servlet Containers. To use it you should import the Servlet HTTP Server Adapter into your project. Check the http_server_servlet module for more information.

HTTP Context

These are the events that the handlers handle (they are also called HTTP calls or just calls along this documentation). They wrap HTTP requests and responses along with some attributes that may be used to pass data across handlers or to signal that a previous callback resulted in an error.

The HTTP context provides you with everything you need to handle an HTTP request. It contains the request, the response, and a bunch of utility methods to return results, read parameters or pass attributes among handlers.

The methods are available directly from the callback. You can check the API documentation for the full list of methods. This sample code illustrates the usage:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
get("/call") {
    attributes          // The attributes list
    attributes["foo"]   // Value of foo attribute

    ok("Response body") // Returns a 200 status
    // return any status (previous return value is ignored here)
    send(
        BAD_REQUEST,
        "Invalid request",
        attributes = attributes + ("A" to "V") // Sets value of attribute A to V
    )
}

Handlers

The main building blocks of Hexagon HTTP services are a set of handlers. A handler is made up of two simple pieces:

  • A predicate: which decides if the handler should be executed for a given request.
  • A callback: code that receives an HTTP context and returns another (or the same) context.

IMPORTANT: the order in which handlers are declared is NOT the order, it is the depth. Handlers are not linked, they are NESTED. The next() method passes control to the next level. If next() is not called in a Handler, following Handlers WON'T be executed (However, the "after" part of already executed Handlers will be run).

For example, this definition:

1
2
3
H1
H2
H3

Is really this execution:

1
2
3
4
5
H1 (on)
  H2 (on)
    H3 (on)
  H2 (after)
H1 (after)

Check the next snippet for Handlers usage examples:

1
2
3
4
5
6
7
get("/hello") { ok("Get greeting") }
put("/hello") { ok("Put greeting") }
post("/hello") { ok("Post greeting") }

on(ALL - GET - PUT - POST, "/hello") { ok("Fallback if HTTP verb was not used before") }

on(status = NOT_FOUND) { ok("Get at '/' if no route matched before") }

Handler Predicates

A predicate is a function that is applied to a call context and returns a boolean. If the result is true, the handler will be executed.

The default implementation (HttpServerPredicate) is based on a template with any combination of the following fields:

  • a list of HTTP methods
  • a path pattern
  • an exception
  • a status

It yields true if all the supplied fields matches a call context.

Path Patterns

Patterns to match requests paths. They can have:

  • Variables: /path/{param}
  • Wildcards: /*/path
  • Regular expresión subset: /(this|that)/path

Handler Types

On Handlers

  • Predicate evaluated at start
  • Executed at the start (before the 'next' handler is called)

After Handlers

  • Predicate evaluated at end (checked on the coming back of the execution next handler)
  • Executed at the end (after 'next' handler has returned)

Filters

You might know filters as interceptors, or middleware from other libraries. Filters are blocks of code executed before and/or after other handlers. They can read the request, read/modify the response, and call the remaining handlers or skip them to halt the call processing.

All filters that match a route are executed in the order they are declared.

Filters optionally take a pattern, causing them to be executed only if the request path matches that pattern.

The following code details filters usage:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
on("/*") { send(headers = response.headers + Header("b-all", "true")) }

on("/filters/*") { send(headers = response.headers + Header("b-filters", "true")) }
get("/filters/route") { ok("filters route") }
after("/filters/*") { send(headers = response.headers + Header("a-filters", "true")) }

get("/filters") { ok("filters") }

path("/nested") {
    on("*") { send(headers = response.headers + Header("b-nested", "true")) }
    on { send(headers = response.headers + Header("b-nested-2", "true")) }
    get("/filters") { ok("nested filters") }
    get("/halted") { send(HttpStatus(499), "halted") }
    get { ok("nested also") }
    after("*") { send(headers = response.headers + Header("a-nested", "true")) }
}

after("/*") { send(headers = response.headers + Header("a-all", "true")) }

Path Handlers

Handlers can be grouped by calling the path() method, which takes a String prefix and gives you a scope to declare other handlers. Ie:

1
2
3
4
5
6
7
8
9
path("/nested") {
    get("/hello") { ok("Greeting") }

    path("/secondLevel") {
        get("/hello") { ok("Second level greeting") }
    }

    get { ok("Get at '/nested'") }
}

If you have a lot of routes, it can be helpful to group them into Path Handlers. You can create path handlers to mount a group of routes in different paths (allowing you to reuse them). Check this snippet:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
fun personRouter(kind: String) = path {
    get { ok("Get $kind") }
    put { ok("Put $kind") }
    post { ok("Post $kind") }
}

val server = HttpServer(serverAdapter()) {
    path("/clients", personRouter("client"))
    path("/customers", personRouter("customer"))
}

Handler Callbacks

Callbacks are request's handling blocks that are bound to handlers. They make the request and response objects available to the handling code.

Callbacks produce a result by returning the received HTTP context with a different response. Callbacks results are the input for the next handler's callbacks in the pipeline.

Request

Request functionality is provided by the request field:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
get("/request") {
    // URL Information
    request.method                   // The HTTP method (GET, ..etc)
    request.protocol                 // HTTP or HTTPS
    request.host                     // The host, e.g. "example.com"
    request.port                     // The server port
    request.path                     // The request path, e.g. /result.jsp
    request.body                     // Request body sent by the client

    method                           // Shortcut of `request.method`
    protocol                         // Shortcut of `request.protocol`
    host                             // Shortcut of `request.host`
    port                             // Shortcut of `request.port`
    path                             // Shortcut of `request.path`

    // Headers
    request.headers                  // The HTTP header list
    request.headers["BAR"]           // First value of BAR header
    request.headers.allValues        // The HTTP header list with their full values list
    request.headers.allValues["BAR"] // List of values of BAR header

    // Common headers shortcuts
    request.contentType              // Content type of request.body
    request.accept                   // Client accepted content types
    request.userAgent()              // User agent (browser requests)
    request.origin()                 // Origin (browser requests)
    request.referer()                // Referer header (page that makes the request)

    accept                           // Shortcut of `request.accept`

    // Parameters
    pathParameters                    // Map with all path parameters
    request.formParameters            // List with all form fields
    request.formParameters.allValues  // Map with all form fields values
    request.queryParameters           // List with all query parameters
    request.queryParameters.allValues // Map with all query parameters values

    queryParameters                   // Shortcut of `request.queryParameters`
    queryParameters.allValues         // Shortcut of `request.queryParameters.allValues`
    formParameters                    // Shortcut of `request.formParameters`
    formParameters.allValues          // Shortcut of `request.formParameters.allValues`

    // Body processing
    request.contentLength             // Length of request body

    ok()
}

Path Parameters

Route patterns can include named parameters, accessible via the pathParameters map on the request object:

Path parameters can be accessed by name or by index.

1
2
3
4
5
get("/pathParam/{foo}") {
    pathParameters["foo"] // Value of foo path parameter
    pathParameters        // Map with all parameters
    ok()
}

Query Parameters

It is possible to access the whole query string or only a specific query parameter using the parameters map on the request object:

1
2
3
4
5
6
7
8
get("/queryParam") {
    request.queryParameters                       // The query param list
    request.queryParameters["FOO"]                // Value of FOO query param
    request.queryParameters.allValues             // The query param list
    request.queryParameters.allValues["FOO"]      // All values of FOO query param

    ok()
}

Form Parameters

HTML Form processing. Don't parse body!

1
2
3
4
5
6
7
get("/formParam") {
    request.formParameters                       // The query param list
    request.formParameters["FOO"]                // Value of FOO query param
    request.formParameters.allValues             // The query param list
    request.formParameters.allValues["FOO"]      // All values of FOO query param
    ok()
}

File Uploads

Multipart Requests

1
2
3
4
post("/file") {
    val filePart = request.partsMap()["file"] ?: error("File not available")
    ok(filePart.body)
}

Response

Response information is provided by the response field:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
get("/response") {
    response.body                       // Get response content
    response.status                     // Get the response status
    response.contentType                // Get the content type

    status                              // Shortcut of `response.status`

    send(
        status = UNAUTHORIZED,          // Set status code to 401
        body = "Hello",                 // Sets content to Hello
        contentType = ContentType(XML), // Set content type to application/xml
        headers = response.headers
            + Header("foo", "bar")      // Sets header FOO with single value bar
            + Header("baz", "1", "2")   // Sets header FOO values with [ bar ]
    )
}

To send error responses:

1
2
3
4
5
6
get("/halt") {
    clientError(UNAUTHORIZED)             // Halt with status
    clientError(UNAUTHORIZED, "Go away!") // Halt with status and message
    internalServerError("Body Message")   // Halt with message (status 500)
    internalServerError()                 // Halt with status 500
}

Redirects

You can redirect requests (returning 30x codes) by using Call utility methods:

1
2
3
get("/redirect") {
    redirect(FOUND, "/call") // browser redirect to /call
}

Cookies

The request and response cookie functions provide a convenient way for sharing information between handlers, requests, or even servers.

You can read client sent cookies from the request's cookies read only map. To change cookies or add new ones you have to use response.addCookie() and response.removeCookie() methods.

Check the following sample code for details:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
get("/cookie") {
    request.cookies                     // Get map of all request cookies
    request.cookiesMap()["foo"]         // Access request cookie by name

    val cookie = HttpCookie("new_foo", "bar")
    ok(
        cookies = listOf(
            cookie,                     // Set cookie with a value
            cookie.copy(maxAge = 3600), // Set cookie with a max-age
            cookie.copy(secure = true), // Secure cookie
            cookie.delete(),            // Remove cookie
        )
    )
}

Error Handling

You can provide handlers for runtime errors. Errors are unhandled exceptions in the callbacks, or handlers returning error codes.

HTTP Errors Handlers

Allow handling responses that returned an HTTP error code. Example:

1
2
3
4
5
6
7
8
exception<Exception>(NOT_FOUND) {
    internalServerError("Root handler")
}

// Register handler for routes halted with 512 code
get("/errors") { send(HttpStatus(512)) }

on(pattern = "*", status = HttpStatus(512)) { send(INTERNAL_SERVER_ERROR, "Ouch") }

Exception Mapping

You can handle previously thrown exceptions of a given type (or subtype). The handler allows you to refer to the thrown exception. Look at the following code for a detailed example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// Register handler for routes which callbacks throw exceptions
get("/exceptions") { error("Message") }
get("/codedExceptions") { send(HttpStatus(509), "code") }

on(pattern = "*", status = HttpStatus(509)) {
    send(HttpStatus(599))
}
on(pattern = "*", exception = IllegalStateException::class) {
    send(HTTP_VERSION_NOT_SUPPORTED, exception?.message ?: "empty")
}

Static Files

You can use a [FileCallback] or a [UrlCallback] to route requests to files or classpath resources.

Those callbacks can point to folders or to files. If they point to a folder, the pattern should have a parameter to provide the file to be fetched inside the folder.

Check the next example for details:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
get("/web/file.txt") { ok("It matches this route and won't search for the file") }

// Expose resources on the '/public' resource folder over the '/web' HTTP path
on(
    status = NOT_FOUND,
    pattern = "/web/*",
    callback = UrlCallback(URL("classpath:public"))
)

// Maps resources on 'assets' on the server root (assets/f.css -> /f.css)
// '/public/css/style.css' resource would be: 'http://{host}:{port}/css/style.css'
on(status = NOT_FOUND, pattern = "/*", callback = UrlCallback(URL("classpath:assets")))

Media Types

The media types of static files are computed from the file extension using the utility methods of the com.hexagonkt.core.media package.

CORS

CORS behaviour can be different depending on the path. You can attach different CORS Callbacks to different handlers. Check the CorsCallback class for more details.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
val path: PathHandler = path {
    corsPath("/default", CorsCallback())
    corsPath("/example/org", CorsCallback("example.org"))
    corsPath("/no/credentials", CorsCallback(supportCredentials = false))
    corsPath("/only/post", CorsCallback(allowedMethods = setOf(POST)))
    corsPath("/cache", CorsCallback(preFlightMaxAge = 10))
    corsPath("/exposed/headers", CorsCallback(exposedHeaders = setOf("head")))
    corsPath("/allowed/headers", CorsCallback(allowedHeaders = setOf("head")))
}

private fun ServerBuilder.corsPath(path: String, cors: CorsCallback) {
    path(path) {
        // CORS settings can change for different routes
        filter(pattern = "*", callback = cors)

        get("/path") { ok(method.toString()) }
        post("/path") { ok(method.toString()) }
        put("/path") { ok(method.toString()) }
        delete("/path") { ok(method.toString()) }
        get { ok(method.toString()) }
        post { ok(method.toString()) }
        put { ok(method.toString()) }
        delete { ok(method.toString()) }
    }
}

HTTPS

It is possible to start a secure server enabling HTTPS. For this, you have to provide a server certificate and its key in the server's SslSettings. Once you use a server certificate, it is also possible to serve content using HTTP/2, for this to work, ALPN is required (however, this is already handled if you use Java 11).

The certificate common name should match the host that will serve the content in order to be accepted by an HTTP client without a security error. There is a Gradle helper to create sample certificates for development purposes.

HTTP clients can also be configured to use a certificate. This is required to implement a double ended authorization (mutual TLS). This is also done by passing an SslSettings object the HTTP client.

If you want to implement mutual trust, you must enforce client certificate in the server configuration (check SslSettings.clientAuth). If this is done, you can access the certificate the client used to connect (assuming it is valid, if not the connection will end with an error) with the Request.certificateChain property.

Below you can find a simple example to set up an HTTPS server and client with mutual TLS:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// Key store files
val identity = "hexagonkt.p12"
val trust = "trust.p12"

// Default passwords are file name reversed
val keyStorePassword = identity.reversed()
val trustStorePassword = trust.reversed()

// Key stores can be set as URIs to classpath resources (the triple slash is needed)
val keyStore = URL("classpath:ssl/$identity")
val trustStore = URL("classpath:ssl/$trust")

val sslSettings = SslSettings(
    keyStore = keyStore,
    keyStorePassword = keyStorePassword,
    trustStore = trustStore,
    trustStorePassword = trustStorePassword,
    clientAuth = true // Requires a valid certificate from the client (mutual TLS)
)

val serverSettings = HttpServerSettings(
    bindPort = 0,
    protocol = HTTPS, // You can also use HTTP2
    sslSettings = sslSettings
)

val server = HttpServer(serverAdapter(), serverSettings) {
    get("/hello") {
        // We can access the certificate used by the client from the request
        val subjectDn = request.certificate()?.subjectX500Principal?.name ?: ""
        val h = response.headers + Header("cert", subjectDn)
        ok("Hello World!", headers = h)
    }
}
server.start()

// We'll use the same certificate for the client (in a real scenario it would be different)
val clientSettings = HttpClientSettings(sslSettings = sslSettings)

// Create an HTTP client and make an HTTPS request
val contextPath = URL("https://localhost:${server.runtimePort}")
val client = HttpClient(clientAdapter(), contextPath, clientSettings)
client.start()
client.get("/hello").apply {
    // Assure the certificate received (and returned) by the server is correct
    assert(headers.require("cert").startsWith("CN=hexagonkt.com"))
    assertEquals("Hello World!", body)
}

Compression

Gzip encoding is supported on the Hexagon Toolkit, however, its implementation depends on the used adapter. To turn on Gzip encoding, you need to enable that feature on the server settings. Check the code below for an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
val serverSettings = HttpServerSettings(
    bindPort = 0,
    features = setOf(ZIP)
)

val server = HttpServer(serverAdapter(), serverSettings) {
    get("/hello") {
        ok("Hello World!")
    }
}
server.start()

val client = HttpClient(clientAdapter(), URL("http://localhost:${server.runtimePort}"))
client.start()

client.get("/hello", HttpFields(Header("accept-encoding", "gzip"))).apply {
    assertEquals(body, "Hello World!")
    assert(headers["content-encoding"]?.contains("gzip") ?: false)
}

client.get("/hello").apply {
    assertEquals(body, "Hello World!")
    assertNull(headers["content-encoding"])
    assertNull(headers["Content-Encoding"])
}

Testing

Integration Tests

To test HTTP servers from outside using a real Adapter, you can create a server setting 0 as port. This will pick a random free port which you can check later:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
val router = path {
    get("/hello") { ok("Hi!") }
}

val bindAddress = InetAddress.getLoopbackAddress()
val serverSettings = HttpServerSettings(bindAddress, 0, banner = "name")
val server = serve(serverAdapter(), listOf(router), serverSettings)

server.use { s ->
    HttpClient(clientAdapter(), URL("http://localhost:${s.runtimePort}")).use {
        it.start()
        assertEquals("Hi!", it.get("/hello").body)
    }
}

To do this kind of tests without creating a custom server (using the real production code). Check the tests of the starter projects.

Mocking Calls

To unit test callbacks and handlers you can create test calls with hardcoded requests without relying on mocking libraries.

For a quick example, check the snipped below:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Test callback (basically, a handler without a predicate)
val callback: HttpCallback = {
    val fakeAttribute = attributes["fake"]
    val fakeHeader = request.headers["fake"]
    ok("Callback result $fakeAttribute $fakeHeader")
}

// You can test callbacks with fake data
val resultContext = callback.process(
    attributes = mapOf("fake" to "attribute"),
    headers = HttpFields(Header("fake", "header"))
)

assertEquals("Callback result attribute header", resultContext.response.bodyString())

// Handlers can also be tested to check predicates along the callbacks
val handler = get("/path", callback)

val notFound = handler.process()
val ok = handler.process(method = GET, path = "/path")

assertEquals(NOT_FOUND, notFound.status)
assertEquals(OK, ok.status)
assertEquals("Callback result null null", ok.bodyString())

Package com.hexagonkt.http.server

This package defines server interfaces for HTTP server adapters.

Package com.hexagonkt.http.server.callbacks

Utility callbacks that can be used on handlers. Reuse a callback in different handlers (after, filter, etc.).

Package com.hexagonkt.http.server.handlers

Contains the HTTP handlers implementation (on top of Core's general event handlers). It houses the HTTP handlers (AfterHandler, OnHandler, PathHandler and FilterHandler) and the HTTP predicate.

Package com.hexagonkt.http.server.model

Classes to model server HTTP messages (requests and responses). Built on top of the http module.