Build Simple Http Server with Kotlin
Add Sparkjava and SLF4J dependencies on your pom.xml
<dependencies>
<dependency>
<groupId>com.sparkjava</groupId>
<artifactId>spark-kotlin</artifactId>
<version>1.0.0-alpha</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.6.4</version>
</dependency>
</dependencies>
Now, let’s create the MyHttpServer class. This class will used for configuring the http server it self.
class MyHttpServer {
companion object{
var instance = MyHttpServer()
}
init {
val port = 1337
val httpService = Service.ignite()
httpService.port(port)
httpService.threadPool(350)
httpService.internalServerError("Error : 500 internal error")
httpService.get("/myhttpserver", MyHttpRoute())
println("Http server running on port : "+port)
}
}
As you can see, we are using port 1337 for port binding of http server, and set 350 thread’s maximum for thread pooling in every request.
Let’s continue with create MyHttpRoute class. This class will used to handle http request and response. Below is the example how to fetch all http get request params and do process for each of the items.
class MyHttpRoute : Route {
override fun handle(request: Request, response: Response): Any {
var respBody = "Params: <br>"
var sumResult = 0
request.queryParams().forEach {
respBody += it+" "+request.queryParams(it)+"<br>"
sumResult = Process.sum(sumResult, request.queryParams(it).toInt())
}
response.body(respBody+"Sum result: "+sumResult)
return response.body()
}
}
And here is the Process class. This class has one static method “sum” for return sum the value of 2 variables.
class Process {
companion object{
fun sum(num1 : Int, num2 : Int) : Int {
return num1 + num2
}
}
}
So, when we access the http with param of integer, the server with give return the sum of all parameter. Let’s check it out
You can see the full project on:
https://github.com/c0deslinger/kotlin-httpserverspark