Hexagon
Hexagon is a microservices toolkit written in Kotlin. Its purpose is to ease the building of services (Web applications or APIs) that run inside a cloud platform.
Install / Use
/learn @hexagontk/HexagonREADME
What is Hexagon
Hexagon is a microservices' toolkit (not a framework) written in Kotlin. Its purpose is to ease the building of server applications (Web applications, APIs or Serverless handlers) that run inside a cloud platform.
The Hexagon Toolkit provides several libraries to build server applications. These libraries provide single standalone features and are referred to as "Ports".
The main ports are:
- The HTTP server: supports HTTPS, HTTP/2, WebSockets, mutual TLS, static files (serve and upload), forms processing, cookies, CORS and more.
- The HTTP client: which supports mutual TLS, HTTP/2, WebSockets, cookies, form fields and files among other features.
- Serialization: provides a common way of using different data formats. Data formats are pluggable and are handled in the same way regardless of their library.
- Template Processing: allows template processing from URLs (local files, resources or HTTP content) binding name patterns to different engines.
Each of these features or ports may have different implementations called "Adapters".
Hexagon is designed to fit in applications that conform to the Hexagonal Architecture (also called Clean Architecture or Ports and Adapters Architecture). Also, its design principles also fits in this architecture.
The Hexagon's goals and design principles are:
-
Put you in Charge: There is no code generation, no runtime annotation processing, no classpath based logic, and no implicit behaviour. You control your tools, not the other way around.
-
Modular: Each feature (Port) or adapter is isolated in its own module. Use only the modules you need without carrying unneeded dependencies.
-
Pluggable Adapters: Every Port may have many implementations (Adapters) using different technologies. You can swap adapters without changing the application code.
-
Batteries Included: It contains all the required pieces to make production-grade applications: logging utilities, serialization, resource handling and build helpers.
-
Native Image: most of the toolkit libraries include GraalVM metadata (check the libraries catalog), native tests are run on CI to ensure native images can be built out of the box.
-
Properly Tested: The project's coverage is checked in every Pull Request. It is also stress-tested at [TechEmpower Frameworks Benchmark][benchmark].
For more information check the Quick Start Guide.
Simple HTTP service
You can clone a starter project (Gradle Starter or Maven Starter). Or you can create a project from scratch following these steps:
-
In Gradle. Import it inside
build.gradle:repositories { mavenCentral() } implementation("com.hexagontk.http:http_server_jetty:$hexagonVersion") -
In Maven. Declare the dependency in
pom.xml:<dependency> <groupId>com.hexagontk.http</groupId> <artifactId>http_server_jetty</artifactId> <version>$hexagonVersion</version> </dependency>
- Write the code in the
src/main/kotlin/Hello.ktfile:
// hello_world
import com.hexagontk.core.media.TEXT_PLAIN
import com.hexagontk.http.model.ContentType
import com.hexagontk.http.server.HttpServer
import com.hexagontk.http.server.HttpServerSettings
import com.hexagontk.http.server.serve
lateinit var server: HttpServer
/**
* Start a Hello World server, serving at path "/hello".
*/
fun main() {
server = serve(JettyServletHttpServer(), HttpServerSettings(bindPort = 0)) {
get("/hello/{name}") {
val name = pathParameters["name"]
ok("Hello $name!", contentType = ContentType(TEXT_PLAIN))
}
}
println("Try it at http://localhost:${server.runtimePort}/hello/World")
}
// hello_world
- Run the service and view the results at: http://localhost:2010/hello
Examples
<details> <summary>Books Example</summary>A simple CRUD example showing how to manage book resources. Here you can check the full test.
// books
data class Book(val author: String, val title: String)
private val books: MutableMap<Int, Book> = linkedMapOf(
100 to Book("Miguel de Cervantes", "Don Quixote"),
101 to Book("William Shakespeare", "Hamlet"),
102 to Book("Homer", "The Odyssey")
)
private val path: PathHandler = path {
post("/books") {
val author = queryParameters["author"]?.text ?: return@post badRequest("Missing author")
val title = queryParameters["title"]?.text ?: return@post badRequest("Missing title")
val id = (books.keys.maxOrNull() ?: 0) + 1
books += id to Book(author, title)
created(id.toString())
}
get("/books/{id}") {
val bookId = pathParameters.require("id").toInt()
val book = books[bookId]
if (book != null)
ok("Title: ${book.title}, Author: ${book.author}")
else
notFound("Book not found")
}
put("/books/{id}") {
val bookId = pathParameters.require("id").toInt()
val book = books[bookId]
if (book != null) {
books += bookId to book.copy(
author = queryParameters["author"]?.text ?: book.author,
title = queryParameters["title"]?.text ?: book.title
)
ok("Book with id '$bookId' updated")
}
else {
notFound("Book not found")
}
}
delete("/books/{id}") {
val bookId = pathParameters.require("id").toInt()
val book = books[bookId]
books -= bookId
if (book != null)
ok("Book with id '$bookId' deleted")
else
notFound("Book not found")
}
// Matches path's requests with *any* HTTP method as a fallback (return 405 instead 404)
after(ALL - DELETE - PUT - GET, "/books/{id}") {
send(METHOD_NOT_ALLOWED_405)
}
get("/books") {
ok(books.keys.joinToString(" ", transform = Int::toString))
}
}
// books
</details>
<details>
<summary>Error Handling Example</summary>
Code to show how to handle callback exceptions and HTTP error codes. Here you can check the full test.
// errors
class CustomException : IllegalArgumentException()
private val path: PathHandler = path {
/*
* Catching `Exception` handles any unhandled exception, has to be the last executed (first
* declared)
*/
exception<Exception> {
internalServerError("Root handler")
}
exception<IllegalArgumentException> {
val error = exception?.message ?: exception?.javaClass?.name ?: fail
val newHeaders = response.headers + Header("runtime-error", error)
send(598, "Runtime", headers = newHeaders)
}
exception<UnsupportedOperationException> {
val error = exception?.message ?: exception?.javaClass?.name ?: fail
val newHeaders = response.headers + Header("error", error)
send(599, "Unsupported", headers = newHeaders)
}
get("/exception") { throw UnsupportedOperationException("error message") }
get("/baseException") { throw CustomException() }
get("/unhandledException") { error("error message") }
get("/invalidBody") { ok(LocalDateTime.now()) }
get("/halt") { internalServerError("halted") }
get("/588") { send(588) }
// It is possible to execute a handler upon a given status code before returning
before(pattern = "*", status = 588) {
send(578, "588 -> 578")
}
}
// errors
</details>
<details>
<summary>Filters Example</summary>
This example shows how to add filters before and after route execution. Here you can check the full test.
// filters
private val users: Map<String, String> = mapOf(
"Turing" to "London",
"Dijkstra" to "Rotterdam"
)
privat
Related Skills
bluebubbles
341.6kUse when you need to send or manage iMessages via BlueBubbles (recommended iMessage integration). Calls go through the generic message tool with channel="bluebubbles".
gh-issues
341.6kFetch GitHub issues, spawn sub-agents to implement fixes and open PRs, then monitor and address PR review comments. Usage: /gh-issues [owner/repo] [--label bug] [--limit 5] [--milestone v1.0] [--assignee @me] [--fork user/repo] [--watch] [--interval 5] [--reviews-only] [--cron] [--dry-run] [--model glm-5] [--notify-channel -1002381931352]
healthcheck
341.6kHost security hardening and risk-tolerance configuration for OpenClaw deployments
node-connect
341.6kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
