Skip to content

Nativeサーバー

KtorはKotlin/Nativeをサポートしており、追加のランタイムや仮想マシンなしでサーバーを実行できます。現在、Kotlin/NativeでKtorサーバーを実行するには、以下の制限があります:

依存関係を追加する

Kotlin/NativeプロジェクトのKtorサーバーには、少なくとも2つの依存関係が必要です: ktor-server-core依存関係とエンジン依存関係(CIO)です。以下のコードスニペットは、build.gradle.ktsファイルのnativeMainソースセットに依存関係を追加する方法を示しています:

kotlin
sourceSets {
    val nativeMain by getting {
        dependencies {
            implementation("io.ktor:ktor-server-core:$ktor_version")
            implementation("io.ktor:ktor-server-cio:$ktor_version")
        }
    }
}

Nativeサーバーをテストするには、ktor-server-test-hostアーティファクトをnativeTestソースセットに追加します:

kotlin
sourceSets {
    val nativeTest by getting {
        dependencies {
            implementation(kotlin("test"))
            implementation("io.ktor:ktor-server-test-host:$ktor_version")
        }
    }
}

ネイティブターゲットを設定する

必要なネイティブターゲットを指定し、binariesプロパティを使用してネイティブバイナリを宣言します:

kotlin
    val arch = System.getProperty("os.arch")
    val nativeTarget = when {
        hostOs == "Mac OS X" && arch == "x86_64" -> macosX64("native")
        hostOs == "Mac OS X" && arch == "aarch64" -> macosArm64("native")
        hostOs == "Linux" && arch == "x86_64" -> linuxX64("native")
        hostOs == "Linux" && arch == "aarch64" -> linuxArm64("native")
        // Other supported targets are listed here: https://ktor.io/docs/native-server.html#targets
        else -> throw GradleException("Host OS is not supported in Kotlin/Native.")
    }

    nativeTarget.apply {
        binaries {
            executable {
                entryPoint = "main"
            }
        }
    }

完全な例は、こちらで確認できます: embedded-server-native

サーバーを作成する

Gradleビルドスクリプトを設定した後、こちらに記載されているようにKtorサーバーを作成できます: サーバーを作成する