Create RouteFood
when you call
http://127.0.0.1:8080/food you can get random food
http://127.0.0.1:8080/food/1 you can get foodlist 2
fun Route.getFood(){
get("/food/{index}"){
try {
val index = call.parameters["index"]?.toInt()
index?.let {
val result = Food.foodList[index]
call.respond(
HttpStatusCode.OK,
result
)
}
}catch (e : IndexOutOfBoundsException){
call.respond(
HttpStatusCode.ExpectationFailed,
"Error:IndexOutOfBoundsException"
)
}catch (e : NumberFormatException){
call.respond(
HttpStatusCode.ExpectationFailed,
"Error:NumberFormatException"
)
}
}
}
fun Route.randomFood(){
get("/food"){
call.respond(
HttpStatusCode.OK,
Food.foodList.random()
)
}
}
Important !!! Is Add this function to ConfigureRouting
fun Application.configureRouting() {
routing {
getFood()
randomFood()
get("/") {
call.respondText("Hello World!")
}
// Static plugin. Try to access `/static/index.html`
static("/static") {
resources("static")
}
}
}
Top comments (0)