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 Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

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

Okay