Skip to content
This repository was archived by the owner on Jan 6, 2025. It is now read-only.

HTTP Server

Matt Anger edited this page Sep 3, 2021 · 2 revisions

A barebones example of how to use AG Server can be found in the example folder of our repo here.

Basics

A basic main function will look something like this:

fun main() {
    val injector = App.createInjector(
       YourModule(),
    )
    val server = App.getServer(injector)
    server.runBlocking()
}

YourModule will be where you tell AG Server about the HTTP Handler you want to add. This is a Guice Module and a basic one could look something like this

class YourModule : AbstractModule() {
    @ProvidesIntoSet
    fun getMyHandler(): HttpHandler {
        return MyHandler()
    }
}

For each of your HTTP Handlers you are adding you will have a similar function that is annotated with @ProvidesIntoSet and returns an object of type HttpHandler. AG Server will collect all of these and add them into its router.

A HttpHandler describes both its prefix, as well as sub routes that it implements.

class MyHandler() : HttpHandler {
    override val pathPrefix: String
        get() = "/hello"

    @Get("/:name")
    suspend fun get(@Param("name") name: String): String {
        return "Hello $name"
    }
}

In this example we define that all the routes this handler provides start with /hello. We also provide one GET route of /:name. This is using the Armeria annotated object style of building routes. So if you spun up a server with this handler and sent a GET request to hostname:port/hello/user you would get back the text Hello user as an http response.

Middleware

Middleware in Armeria are known as decorators. We provide a method by which you can inject decorators into the Server.

class YourModule : AbstractModule() {
    @ProvidesIntoSet
    fun getDecorators(): List<HttpDecorator> {
        return listOf(
          decorator1(),
          decorator2(),
        )
    }
}

The list of decorators will be executed in the order you provide them in the list (which is why it's not just a set, as sets are unordered). You can read more about Armeria decorators here.

Clone this wiki locally