DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

Andrei
Andrei

Posted on • Originally published at Medium on

Kottpd โ€” HTTP Server in pure Kotlin

In todayโ€™s post I would like to talk about one of the projects Iโ€™m working on. I define it as light HTTP framework and it is made in pure Kotlin. Based on these two facts Iโ€™ve named itย kottpd.

This project was born during long bus ride. There was no Internet and I decided to write something without external dependencies. What could be better then implementing well-known text-based protocol?!

Not all pieces were easy to find in the palaces of the mind but in couple of hours first version was ready to serve standard HTTP queries. The design of API was made with inspiration from Spark-Java. So, it looks quiteย similar.

What we could find under the hood? First of all it is Cached ThreadsPool. It helps to allocate and reuse threads for each HTTP request. Then in infinite loop the server waits for incoming connections, reads it, tries to match against configured routes and passes to corresponding handler if found. Beside request handlers you could also specify Before and After filters to implement some sort of middleware(for exampleโ€Šโ€”โ€Šlogin, transactions, etc.).

What for is itย useful?

Well, it could be used if you want to make a web application, or an REST API , or just to serve a static content(it supports that too!). But you want to do it in a lightweight way. And you like Kotlin! That it is a perfect choice for you. Have I mentioned it supportsย  SSL?

To explain it better let me show you an example that could be easily found in the README file. But first of all you need to add it as a dependency to your project. The library is published into maven central repository, so you should not face any issues withย it.

Here we create an instance of Server class, define path to the folder with static content we want our server to serve. Then we define several request handlers(yes, you could use regular expressions for that). And then there is a block with filters. They could be globalโ€Šโ€”โ€Šwhen there is no specific path definedโ€Šโ€”โ€Šand path specific. And of course you could define some exception handlers too. The only thing is left to be doneโ€Šโ€”โ€Šcall start() method. By default your application will listen on the port 9000. But you could just pass any port value you want as argument to start() method or define it with server.port system property(-Dserver.port=8080).

Conclusion

I hope you got interested with my project. Please, try to use it in your applications and I will be really happy to see any feedback from you. If you have never used Kotlin before, it is a good moment toย start!

Do Kotlinโ€Šโ€”โ€Šdo theย Web!

Top comments (0)

๐ŸŒš Life is too short to browse without dark mode