Ktor 練功場筆記(1) 新建Ktor專案

Andy Lu
4 min readAug 2, 2020

Kotlin第二次讀書會

什麼是Ktor

Ktor是用Kotlin作為開發語言的一個framework,在連接的系統中建立非同步的server與client。

Ktor允許應用程式(application)使用Jetty, Netty 或 CIO 在與Servlet兼容的應用程式伺服器(Application Server)(如Tomcat)中運行,或作為嵌入式應用程式運行。

環境設定

利用最新版本的IntelliJ IDEA加上Ktor plugin即可開始。文章編寫時版本如下:

  1. IntelliJ IDEA: 2020.1.3
  2. Ktor plugin: 1.3.2–1: 參考
  • IntelliJ IDEA → Preferences… → Plugins → Install JetBrains Plugin… → Ktor → Install

建立新專案

  1. 開啟新專案(File → New → Project)
  2. 如果Ktor Plugin已安裝完成,左邊框架/語言選擇欄中將出現Ktor選項。
  3. 在Server欄選擇CSS DSL;Client欄選擇Apache HttpClient Engine。如下圖:

4. 點選Next之後,輸入Group Id, ArtifactId以及版號,若不修改,使用預設值即可。

6. 點選Next之後,依照需求填入Project name 以及 Project location。

7. 點選 Finish 完成專案設定。

執行專案

不像其他直譯語言,ktor需要先將程式碼編譯過才能執行。

方法1:在Terminal中,直接輸入 gradle run 或是 (./gradlew run)

方法2:在IntelliJ IDEA中,選擇Run→Run,選擇需要執行的Application。

(在專案開啟之後,會在src目錄底下建立一個預設的Application(Application.kt)

方法3:在Toolbar 選擇 Gradle → Tasks → application → run

測試是否正確

將Application運行後,若成功運行,在terminal 將會顯示底下這段訊息。

接者,我們可以使用瀏覽器開啟 http://127.0.0.1:8080,測試是否有出現 HELLO WORLD!

小記

本次的練功坊帶了我們安裝Ktor plugin,同時運行一個簡單的Application。

那麼為什麼進入http://127.0.0.1:8080 就可以看到HELLO WORLD!呢?可以進入src/Application.kt中看看。

在Application.kt中,我們可以發現在 routing的方法中,有好幾個 get的方法在其中,其中第一個 get的第一個參數帶入了 "/”,以及第二個參數帶入了 call.respondText("HELLO WORLD!", contentType = ContentType.Text.Plain)

所以進入我們的Application Server的root目錄,就會顯示HELLO WORLD!的文字。

好的,今天的筆記到這邊,謝謝各位

參考

Ktor官網

Git hub: https://github.com/andyludeveloper/ktor_workshop

--

--

Andy Lu
Andy Lu

Written by Andy Lu

Android/Flutter developer, Kotlin Expert, like to learn and share.

No responses yet