DEV Community

LiHan
LiHan

Posted on

1

[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

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay