Andrei
Posted on March 3, 2018
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!
Posted on March 3, 2018
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.