All Projects → hexagonkt → Hexagon

hexagonkt / Hexagon

Licence: mit
Hexagon is a microservices toolkit written in Kotlin. Its purpose is to ease the building of services (Web applications, APIs or queue consumers) that run inside a cloud platform.

Programming Languages

kotlin
9241 projects

Projects that are alternatives of or similar to Hexagon

Armeria
Your go-to microservice framework for any situation, from the creator of Netty et al. You can build any type of microservice leveraging your favorite technologies, including gRPC, Thrift, Kotlin, Retrofit, Reactive Streams, Spring Boot and Dropwizard.
Stars: ✭ 3,392 (+909.52%)
Mutual labels:  microservices, hacktoberfest, micro-framework
Blog Service
blog service @nestjs
Stars: ✭ 188 (-44.05%)
Mutual labels:  mongodb, travis-ci, codecov
Hippo
💨A well crafted go packages that help you build robust, reliable, maintainable microservices.
Stars: ✭ 134 (-60.12%)
Mutual labels:  microservices, toolkit, rabbitmq
Mongo Sync
Sync Remote and Local MongoDB Databases 🔥
Stars: ✭ 293 (-12.8%)
Mutual labels:  hacktoberfest, mongodb
Covr
Test coverage reports for R
Stars: ✭ 285 (-15.18%)
Mutual labels:  travis-ci, codecov
Surging
Surging is a micro-service engine that provides a lightweight, high-performance, modular RPC request pipeline. The service engine supports http, TCP, WS,Grpc, Thrift,Mqtt, UDP, and DNS protocols. It uses ZooKeeper and Consul as a registry, and integrates it. Hash, random, polling, Fair Polling as a load balancing algorithm, built-in service gove…
Stars: ✭ 3,088 (+819.05%)
Mutual labels:  microservices, rabbitmq
microframeworks-showcase
A simple grocery list webapplication implemented with the Microframeworks Spark Java, Jodd, Ninja, Javalite, Pippo and Ratpack
Stars: ✭ 29 (-91.37%)
Mutual labels:  gradle, micro-framework
Awesome Minimalist
A curated list of awesome minimalist frameworks (simple and lightweight).
Stars: ✭ 3,189 (+849.11%)
Mutual labels:  hacktoberfest, micro-framework
Yii2 Mongodb
Yii 2 MongoDB extension
Stars: ✭ 299 (-11.01%)
Mutual labels:  hacktoberfest, mongodb
Docs
Java知识总结:MySQL实战45讲,多线程和JVM知识总结,,SpringBoot,SpringCloud,Storm系列,微信小程序开发,ELK,《JAVA核心技术36讲笔记》,《深入理解JVM虚拟机笔记》,《高性能MySQL笔记》,《数据结构与算法》等等
Stars: ✭ 308 (-8.33%)
Mutual labels:  mongodb, jvm
Gokit
Go Examples: From basics to distributed systems
Stars: ✭ 325 (-3.27%)
Mutual labels:  microservices, mongodb
Secretz
secretz, minimizing the large attack surface of Travis CI
Stars: ✭ 279 (-16.96%)
Mutual labels:  hacktoberfest, travis-ci
Travis Ci Discord Webhook
⛓ Here's your serverless solution for sending build status from Travis CI to Discord as webhooks.
Stars: ✭ 273 (-18.75%)
Mutual labels:  hacktoberfest, travis-ci
core
Microservice abstract class
Stars: ✭ 37 (-88.99%)
Mutual labels:  rabbitmq, toolkit
Vertx Zero
Zero Framework:http://www.vertxup.cn
Stars: ✭ 320 (-4.76%)
Mutual labels:  microservices, mongodb
Dotenv Kotlin
🗝️ Dotenv is a module that loads environment variables from a .env file
Stars: ✭ 326 (-2.98%)
Mutual labels:  hacktoberfest, jvm
Minecolonies
Minecolonies minecraft mod
Stars: ✭ 303 (-9.82%)
Mutual labels:  gradle, hacktoberfest
Cpp Project
Boiler plate template for C++ projects, with CMake, Doctest, Travis CI, Appveyor, Github Actions and coverage reports.
Stars: ✭ 328 (-2.38%)
Mutual labels:  travis-ci, codecov
phpunit-travis-ci-coverage-example
phpUnit Testing on Travis-CI with Code Coverage on CodeCov
Stars: ✭ 30 (-91.07%)
Mutual labels:  travis-ci, codecov
cpp14-project-template
A simple, cross-platform, and continuously integrated C++14 project template
Stars: ✭ 64 (-80.95%)
Mutual labels:  travis-ci, codecov

Hexagon
Hexagon

The atoms of your platform

GitHub Actions Coverage Maven Central Repository

Home Site | Quick Start | Developer Guide


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, sessions, CORS and more.
  • The HTTP client: which supports mutual TLS, HTTP/2 and cookies among other things.

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: settings management, serialization, dependency injection 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 or the Developer 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
package com.hexagonkt.http.server.jetty

import com.hexagonkt.http.server.Server

lateinit var server: Server

fun main() {
    server = Server(JettyServletAdapter()) {
        get("/hello") {
            ok("Hello World!")
        }
    }

    server.start()
}
// hello
  1. Run the service and view the results at: http://localhost:2010/hello/world

Examples

Books Example

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")
)

val server: Server = Server(adapter) {
    post("/books") {
        // Require fails if parameter does not exists
        val author = queryParameters.require("author")
        val title = queryParameters.require("title")
        val id = (books.keys.max() ?: 0) + 1
        books += id to Book(author, title)
        send(201, id)
    }

    get("/books/{id}") {
        val bookId = pathParameters.require("id").toInt()
        val book = books[bookId]
        if (book != null)
            // ok() is a shortcut to send(200)
            ok("Title: ${book.title}, Author: ${book.author}")
        else
            send(404, "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"] ?: book.author,
                title = queryParameters["title"] ?: book.title
            )

            ok("Book with id '$bookId' updated")
        }
        else {
            send(404, "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
            send(404, "Book not found")
    }

    // Matches path's requests with *any* HTTP method as a fallback (return 404 instead 405)
    any("/books/{id}") { send(405) }

    get("/books") { ok(books.keys.joinToString(" ", transform = Int::toString)) }
}
// books
Session Example

Example showing how to use sessions. Here you can check the full test.

// session
val server: Server = Server(adapter) {
    path("/session") {
        get("/id") { ok(session.id ?: "null") }
        get("/access") { ok(session.lastAccessedTime?.toString() ?: "null") }
        get("/new") { ok(session.isNew()) }

        path("/inactive") {
            get { ok(session.maxInactiveInterval ?: "null") }

            put("/{time}") {
                session.maxInactiveInterval = pathParameters.require("time").toInt()
            }
        }

        get("/creation") { ok(session.creationTime ?: "null") }
        post("/invalidate") { session.invalidate() }

        path("/{key}") {
            put("/{value}") {
                session.set(pathParameters.require("key"), pathParameters.require("value"))
            }

            get { ok(session.get(pathParameters.require("key")).toString()) }
            delete { session.remove(pathParameters.require("key")) }
        }

        get {
            val attributes = session.attributes
            val attributeTexts = attributes.entries.map { it.key + " : " + it.value }

            response.headers["attributes"] = attributeTexts.joinToString(", ")
            response.headers["attribute values"] = attributes.values.joinToString(", ")
            response.headers["attribute names"] = attributes.keys.joinToString(", ")

            response.headers["creation"] = session.creationTime.toString()
            response.headers["id"] = session.id ?: ""
            response.headers["last access"] = session.lastAccessedTime.toString()

            response.status = 200
        }
    }
}
// session
Error Handling Example

Code to show how to handle callback exceptions and HTTP error codes. Here you can check the full test.

// errors
class CustomException : IllegalArgumentException()

val server: Server = Server(adapter) {
    error(UnsupportedOperationException::class) {
        response.headers["error"] = it.message ?: it.javaClass.name
        send(599, "Unsupported")
    }

    error(IllegalArgumentException::class) {
        response.headers["runtimeError"] = it.message ?: it.javaClass.name
        send(598, "Runtime")
    }

    // Catching `Exception` handles any unhandled exception before (it has to be the last)
    error(Exception::class) { send(500, "Root handler") }

    // It is possible to execute a handler upon a given status code before returning
    error(588) { send(578, "588 -> 578") }

    get("/exception") { throw UnsupportedOperationException("error message") }
    get("/baseException") { throw CustomException() }
    get("/unhandledException") { error("error message") }

    get("/halt") { halt("halted") }
    get("/588") { halt(588) }
}
// errors
Filters Example

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 server: Server = Server(adapter) {
    before { attributes["start"] = nanoTime() }

    before("/protected/*") {
        val authorization = request.headers["Authorization"] ?: halt(401, "Unauthorized")
        val credentials = authorization.removePrefix("Basic ")
        val userPassword = String(Base64.getDecoder().decode(credentials)).split(":")

        // Parameters set in call attributes are accessible in other filters and routes
        attributes["username"] = userPassword[0]
        attributes["password"] = userPassword[1]
    }

    // All matching filters are run in order unless call is halted
    before("/protected/*") {
        if(users[attributes["username"]] != attributes["password"])
            halt(403, "Forbidden")
    }

    get("/protected/hi") { ok("Hello ${attributes["username"]}!") }

    // After filters are ran even if request was halted before
    after { response.headers["time"] = nanoTime() - attributes["start"] as Long }
}
// filters
Files Example

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

// files
private val server: Server = Server(adapter) {
    path("/static") {
        get("/files/*", Resource("assets")) // Serve `assets` resources on `/html/*`
        get("/resources/*", File(directory)) // Serve `test` folder on `/pub/*`
    }

    get("/html/*", Resource("assets")) // Serve `assets` resources on `/html/*`
    get("/pub/*", File(directory)) // Serve `test` folder on `/pub/*`
    get(Resource("public")) // Serve `public` resources folder on `/*`

    post("/multipart") { ok(request.parts.keys.joinToString(":")) }

    post("/file") {
        val part = request.parts.values.first()
        val content = part.inputStream.reader().readText()
        ok(content)
    }

    post("/form") {
        fun serializeMap(map: Map<String, List<String>>): List<String> = listOf(
            map.map { "${it.key}:${it.value.joinToString(",")}}" }.joinToString("\n")
        )

        val queryParams = serializeMap(queryParametersValues)
        val formParams = serializeMap(formParametersValues)

        response.headersValues["queryParams"] = queryParams
        response.headersValues["formParams"] = formParams
    }
}
// files

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

Thanks

This project is supported by:

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 ✌️.

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 Project Board and the Organization Board at GitHub.

You can ask any question, suggestion or complaint at the project's Slack channel. You can be up to date of project's news following @hexagon_kt on 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.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].