DEV Community

LiHan
LiHan

Posted on

[ktor] Create Fun To Get Food - Part 2

Create RouteFood

when you call

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()
        )
    }
}
Enter fullscreen mode Exit fullscreen mode

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")
    }
}
Enter fullscreen mode Exit fullscreen mode

}

Final

result-1

result-2

Top comments (0)