hexagon

hexagon

用Kotlin构建的模块化微服务工具包 简化云应用开发

Hexagon是一款Kotlin微服务工具包,致力于简化云平台服务器应用开发。它包含HTTP服务器、HTTP客户端和模板处理等多个独立功能库。基于六边形架构,Hexagon注重模块化和可插拔适配器设计。这个专为Kotlin打造的工具包拥有完善的测试覆盖,并在TechEmpower基准测试中展示了其性能实力。

<h3 align="center"> <a href="https://hexagontk.com"> <img alt="Hexagon" src="https://hexagontk.com/tile-small.png" /> </a> <br> Hexagon </h3> <h4 align="center">The atoms of your platform</h4> <p align="center"> <a href="https://github.com/hexagontk/hexagon/actions"> <img alt="GitHub Actions" src="https://github.com/hexagontk/hexagon/workflows/Release/badge.svg" /> </a> <a href="https://hexagontk.com/jacoco"> <img src="https://hexagontk.com/img/coverage.svg" alt="Coverage" /> </a> <a href="https://search.maven.org/search?q=g:com.hexagonkt"> <img src="https://hexagontk.com/img/download.svg" alt="Maven Central Repository" /> </a> </p> <p align="center"> <a href="https://hexagontk.com">Home Site</a> | <a href="https://hexagontk.com/quick_start">Quick Start</a> </p>

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 queue consumers) 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, mutual TLS, static files (serve and upload), forms processing, cookies, CORS and more.
  • The HTTP client: which supports mutual TLS, HTTP/2, cookies, form fields and files among other features.
  • 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.

  • Kotlin First: Take full advantage of Kotlin instead of just calling Java code from Kotlin. The library is coded in Kotlin for coding with Kotlin. No strings attached to Java (as a Language).

  • Properly Tested: The project's coverage is checked in every Pull Request. It is also stress-tested at TechEmpower Frameworks 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:

  1. Configure Kotlin in Gradle or Maven.
  2. Add the dependency:
  • In Gradle. Import it inside build.gradle:

    repositories { mavenCentral() } implementation("com.hexagonkt:http_server_jetty:$hexagonVersion")
  • In Maven. Declare the dependency in pom.xml:

    <dependency> <groupId>com.hexagonkt</groupId> <artifactId>http_server_jetty</artifactId> <version>$hexagonVersion</version> </dependency>
  1. Write the code in the src/main/kotlin/Hello.kt file:
// hello_world import com.hexagonkt.core.media.TEXT_PLAIN import com.hexagonkt.http.model.ContentType import com.hexagonkt.http.server.HttpServer import com.hexagonkt.http.server.jetty.serve lateinit var server: HttpServer /** * Start a Hello World server, serving at path "/hello". */ fun main() { server = serve { get("/hello/{name}") { val name = pathParameters["name"] ok("Hello $name!", contentType = ContentType(TEXT_PLAIN)) } } } // hello_world
  1. 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"]?.string() ?: return@post badRequest("Missing author") val title = queryParameters["title"]?.string() ?: 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"]?.string() ?: book.author, title = queryParameters["title"]?.string() ?: 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}", status = NOT_FOUND_404) { 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(HttpStatus(598), "Runtime", headers = newHeaders) } exception<UnsupportedOperationException> { val error = exception?.message ?: exception?.javaClass?.name ?: fail val newHeaders = response.headers + Header("error", error) send(HttpStatus(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(HttpStatus(588)) } // It is possible to execute a handler upon a given status code before returning before(pattern = "*", status = HttpStatus(588)) { send(HttpStatus(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" ) private val path: PathHandler = path { filter("*") { val start = System.nanoTime() // Call next and store result to chain it val next = next() val time = (System.nanoTime() - start).toString() // Copies result from chain with the extra data next.send(headers = response.headers + Header("time", time)) } filter("/protected/*") { val authorization = request.authorization ?: return@filter unauthorized("Unauthorized") val credentials = authorization.value val userPassword = String(credentials.decodeBase64()).split(":") // Parameters set in call attributes are accessible in other filters and routes send(attributes = attributes + ("username" to userPassword[0]) + ("password" to userPassword[1]) ).next() } // All matching filters are run in order unless call is halted filter("/protected/*") { if(users[attributes["username"]] != attributes["password"]) send(FORBIDDEN_403, "Forbidden") else next() } get("/protected/hi") { ok("Hello ${attributes["username"]}!") } path("/after") { after(PUT) { send(ALREADY_REPORTED_208) } after(PUT, "/second") { send(NO_CONTENT_204) } after("/second") { send(CREATED_201) } after { send(ACCEPTED_202) } } } // filters
</details> <details> <summary>Files Example</summary>

The following code shows how to serve resources and receive files. Here you can check the full test.

// files private val path: PathHandler = path { // Serve `public` resources folder on `/*` after( methods = setOf(GET), pattern = "/*", status = NOT_FOUND_404, callback = UrlCallback(urlOf("classpath:public")) ) path("/static") { get("/files/*", UrlCallback(urlOf("classpath:assets"))) get("/resources/*", FileCallback(File(directory))) } get("/html/*", UrlCallback(urlOf("classpath:assets"))) // Serve `assets` files on `/html/*` get("/pub/*", FileCallback(File(directory))) // Serve `test` folder on `/pub/*` post("/multipart") { val headers = parts.first().let { p -> val name = p.name val bodyString = p.bodyString() val size = p.size.toString() Headers( Header("name", name), Header("body", bodyString), Header("size", size), ) } ok(headers = headers) } post("/file") { val part = parts.first() val content = part.bodyString() val submittedFile = part.submittedFileName ?: "" ok(content, headers = response.headers + Header("submitted-file", submittedFile)) } post("/form") { fun <T : HttpField> serializeMap(map: Collection<T>): List<String> = listOf( map.joinToString("\n") { "${it.name}:${it.values.joinToString(",")}" } ) val queryParams = serializeMap(queryParameters.values) val formParams = serializeMap(formParameters.values) val headers = Headers(Header("query-params", queryParams), Header("form-params", formParams)) ok(headers = response.headers + headers) } } // files
</details>

You can check more sample projects and snippets at the examples page.

Thanks

This project is supported by:

<a href="https://www.digitalocean.com/?utm_medium=opensource&utm_source=Hexagon-Toolkit"> <img height="128px" src= "https://opensource.nyc3.cdn.digitaloceanspaces.com/attribution/assets/SVG/DO_Logo_vertical_blue.svg"> </a> <a href="https://www.jetbrains.com/?from=Hexagon-Toolkit"> <img height="96px" src="https://hexagontk.com/img/sponsors/jetbrains-variant-4.svg"> </a>

Status

The toolkit is properly tested. This is the coverage report:

Coverage

Performance is not the primary goal, but it is taken seriously. You can check performance numbers in the TechEmpower Web Framework Benchmarks.

Contribute

If you like this project and want to support it, the easiest way is to give it a star :v:.

If you feel like you can do more. You can contribute to the project in different ways:

To know what issues are currently open and be aware of the next features you can check the Organization Board at GitHub.

You can ask any question, suggestion or complaint at the project's discussions. You can be up-to-date of project's news following @hexagontk on X (Twitter).

Thanks to all project's contributors!

CodeTriage

License

The project is licensed under the [MIT License]. This license lets you use the source for free or commercial purposes as long as you provide attribution and don’t hold any project member liable.

[MIT License]:

编辑推荐精选

TRAE编程

TRAE编程

AI辅助编程,代码自动修复

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

AI工具TraeAI IDE协作生产力转型热门
商汤小浣熊

商汤小浣熊

最强AI数据分析助手

小浣熊家族Raccoon,您的AI智能助手,致力于通过先进的人工智能技术,为用户提供高效、便捷的智能服务。无论是日常咨询还是专业问题解答,小浣熊都能以快速、准确的响应满足您的需求,让您的生活更加智能便捷。

imini AI

imini AI

像人一样思考的AI智能体

imini 是一款超级AI智能体,能根据人类指令,自主思考、自主完成、并且交付结果的AI智能体。

Keevx

Keevx

AI数字人视频创作平台

Keevx 一款开箱即用的AI数字人视频创作平台,广泛适用于电商广告、企业培训与社媒宣传,让全球企业与个人创作者无需拍摄剪辑,就能快速生成多语言、高质量的专业视频。

即梦AI

即梦AI

一站式AI创作平台

提供 AI 驱动的图片、视频生成及数字人等功能,助力创意创作

扣子-AI办公

扣子-AI办公

AI办公助手,复杂任务高效处理

AI办公助手,复杂任务高效处理。办公效率低?扣子空间AI助手支持播客生成、PPT制作、网页开发及报告写作,覆盖科研、商业、舆情等领域的专家Agent 7x24小时响应,生活工作无缝切换,提升50%效率!

蛙蛙写作

蛙蛙写作

AI小说写作助手,一站式润色、改写、扩写

蛙蛙写作—国内先进的AI写作平台,涵盖小说、学术、社交媒体等多场景。提供续写、改写、润色等功能,助力创作者高效优化写作流程。界面简洁,功能全面,适合各类写作者提升内容品质和工作效率。

AI辅助写作AI工具蛙蛙写作AI写作工具学术助手办公助手营销助手AI助手
问小白

问小白

全能AI智能助手,随时解答生活与工作的多样问题

问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。

热门AI助手AI对话AI工具聊天机器人
Transly

Transly

实时语音翻译/同声传译工具

Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。

讯飞智文

讯飞智文

一键生成PPT和Word,让学习生活更轻松

讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。

AI办公办公工具AI工具讯飞智文AI在线生成PPTAI撰写助手多语种文档生成AI自动配图热门
下拉加载更多