建立完 Ktor 3 的專案並且能在本地運作之後,我們來看看專案內的結構如何
首先我們看 src/main/kotlin/Application.kt
fun main(args: Array<String>) {
io.ktor.server.netty.EngineMain.main(args)
}
fun Application.module() {
configureSerialization()
configureDatabases()
configureRouting()
}
這邊的寫法和之前差異不大,一樣是利用 extended function 來延伸 Application 的功能。
不過由於我們這次多安裝了幾個套件,所以路由的部分也加上了幾個
我們來看看 src/main/kotlin/Routing.kt,routing {}
的部分和之前差不多
routing {
get("/") {
call.respondText("Hello World!")
}
不過我們注意到 Application.configureRouting()
裡面多安裝了一個物件
install(StatusPages) {
exception<Throwable> { call, cause ->
call.respondText(text = "500: $cause" , status = HttpStatusCode.InternalServerError)
}
}
這個就是昨天我們在建立專案時安裝的 StatusPages 這個套件,可以在我們收到例外時回傳我們設定的錯誤訊息。
這邊的設定會將例外內的 cause
放在文字內回傳出來。
如果我們將原本的
get("/") {
call.respondText("Hello World!")
}
改成
get("/") {
throw RuntimeException("一般例外")
}
重新編譯後存取 http://0.0.0.0:8080/,我們就會看到
500: java.lang.RuntimeException: 一般例外
接著我們看到
staticResources("/static", "static")
這是 Static Resources 幫我們建立的路由,可以將靜態檔案直接提供給前端。
接著我們往下看,可以看到一個 Articles
類別
@Serializable
@Resource("/articles")
class Articles(val sort: String? = "new")
這個類別上面加上了 kotlinx.serialization.Serializable
annotation class,只需要加上這個標記,我們就讓這個類別可以被序列化。
這邊包含了一個屬性 sort
,預設為 new
在下面這個路由
get<Articles> { article ->
// Get all articles ...
call.respond("List of articles sorted starting from ${article.sort}")
}
Kotlin 會試著將網址輸入的 parameter 轉換成 Articles
物件,並輸入程式內進行後續的操作
所以當我們試著存取 http://0.0.0.0:8080/articles
會看到
List of articles sorted starting from new
但是如果我們存取 http://0.0.0.0:8080/articles?sort=test
,由於程式內的 article
已經被我們從網址上改變,就會看到
List of articles sorted starting from test
今天的內容就到這邊,我們明天見!