First, create a main method. The main method should create a WebServer instance, add the services or controllers, and start the server.
In the example below, we add a dummy service returning "Welcome to Thorium!" at http://localhost:8080.
import com.greenfossil.thorium.{*, given}
@main def start: Unit = Server(8080)
.addService("/", Action(request => "Welcome to Thorium!"))
.start()
To run the server and check if it is accessible, run the main method in IntelliJ IDEA or use the run command in your sbt shell.
Last modified on 12/12/2022, 10:45 amNext is to create a controller. We shall create a simple controller with just one method:
import com.linecorp.armeria.server.annotation.{Get, Param}
object SimpleController:
@Get("/sayHello/:name")
def sayHello(@Param name: String)(using request: Request) =
s"Hello $name"
Another way to write the controller method above is as below:
import com.greenfossil.thorium.{*, given}
import com.linecorp.armeria.server.annotation.{Get, Param}
object SimpleController:
@Get("/sayHello/:name")
def sayHello(@Param name: String) = Action{request =>
s"Hello $name"
}
In the main method, remove the dummy service and add the new controller.
import com.greenfossil.thorium.{*, given}
import controllers.SimpleController
@main def start: Unit =
Server(8080)
.addServices(SimpleController)
.start()
Last modified on 12/12/2022, 10:46 am To handle submitted data from POST requests, you can use the data-mapping library which is bundled with web-server.
Shown below is a simple form that accepts two fields:
val userForm: Mapping[(String, String)] = tuple(
"firstname" -> text,
"lastname" -> text
)
Create a POST controller method and use bindFromRequest() to retrieve data from POST request.
@Post("/createUser")
def createUser(using request: Request) =
userForm.bindFromRequest().fold(
errorForm => {
val errorMessage = errorForm.errors.map { error =>
s"Field ${error.key} has error: ${error.message}"
}.mkString(". ")
BadRequest(errorMessage)
},
{
case (firstname, lastname) =>
Ok(s"Hello, $firstname, $lastname!")
}
)
To test this endpoint, you can use this curl command in the terminal:
curl -d firstname=john -d lastname=doe http://localhost:8080/createUser
If you see the server response with the text "Hello, john, doe!", it means the form has retrieved data successfully.
This library can also handle POST requests with JSON content type. This command will give you the same result:curl -H 'Content-Type: application/json' -d '{"firstname":"john", "lastname":"doe"}' http://localhost:8080/createUser
Last modified on 14/11/2022, 5:08 am To redirect to another controller, simply use the Redirect method
import com.greenfossil.thorium.{*, given}
import com.linecorp.armeria.server.annotation.{Get, Param}
object SimpleController:
@Get("/sayHello/:name")
def sayHello(@Param name: String)(using request: Request) =
s"Hello $name"
@Get("/redirect")
def redirect(using request: Request) =
Redirect(sayHello("User"))
Last modified on 07/12/2022, 4:03 pm