https://kotlinlang.org logo
Docs
Join the conversationJoin Slack
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by Linen
ktor
  • j

    Jeff

    06/10/2021, 9:14 AM
    I want to use an alias for the order by clause in Exposed Kotlin like so:
    6371 * ACOS(COS(RADIANS(:latitude)) * COS(RADIANS(`lat`)) * COS(RADIANS(:longitude) - RADIANS(`lng`)) + SIN(RADIANS(:latitude)) * SIN(RADIANS(`lat`))) AS `distance`
    Anyone with an idea on how to implement this?
    c
    2 replies · 2 participants
  • m

    ms

    06/10/2021, 10:03 AM
    https://kotlinlang.slack.com/archives/C0A974TJ9/p1619618607459400?thread_ts=1619618607.459400&cid=C0A974TJ9 Any ETA on this @hhariri
    h
    d
    3 replies · 3 participants
  • a

    Ankit Dubey

    06/11/2021, 4:31 AM
    Hi everyone, I’m facing error while calling Ktor API
    SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
    SLF4J: Defaulting to no-operation (NOP) logger implementation
    This error doesn’t come when i pass HashMap<String, String> to body But whenever i’m passing,
    HashMap<String, Any>
    then only getting error. Any idea? Do I need to add SLF4J dependency🤔
    a
    r
    7 replies · 3 participants
  • t

    tim

    06/11/2021, 11:40 AM
    Hi is there an easy way for the ktor http client to accept self signed certs for dev?
    d
    a
    3 replies · 3 participants
  • c

    CLOVIS

    06/12/2021, 1:35 PM
    It's really nice of Ktor to use different defaults for serialization on the client-side and on the server-side. Just took me about a day to understand why KotlinX.Serialization wouldn't work. Ktor 1.6.0 server-side,
    JsonSupport.kt:54
    useArrayPolymorphism = true
    Ktor 1.6.0 client-side,
    KotlinxSerializer.kt:64
    useArrayPolymorphism = false
    Where should I report that? GitHub, YouTrack?
    👍 1
    j
    a
    4 replies · 3 participants
  • d

    divyanshunegi

    06/12/2021, 5:33 PM
    This might sound a noob question but just starting on KMM, I want to create an APIClient as shared module for Android and iOS I need the following features in my
    Ktor
    Implementation. • It should have local SSL data encryption • InternetConnectionCheck Interceptor • ErrorHandlerInterceptor • RetryRequest After RefreshToken Interceptor • Few other custom interceptors Earlier I was writing my APiClient in the
    commonMain
    but as I can see it does not support addInterceptor property by default, which is available in OkHttp for Android. So the new plan I had is create an expect class APiClient in common main and implement APIClient for Android on AndroidMain with OkHttp engine and APiClient on iOSMain with IOS Engine. Is this approach right ? or am I missing some part ?
    x
    1 reply · 2 participants
  • t

    tylerwilson

    06/14/2021, 3:48 PM
    Before wasting time, can I use Ktor in a watchOS app/target?
    t
    20 replies · 2 participants
  • p

    Pavel Petkevich

    06/14/2021, 7:14 PM
    🤞✌️
    c
    d
    2 replies · 3 participants
  • m

    MBegemot

    06/15/2021, 4:42 PM
    After updating to latest ver, I have huge problems with proguard ClassCastException and class cannot be cast to reflect.parametrized tipe, I have the feeling that it's more a ktor issue but not sure, debuging this kind of stuff its kind a hell ... specially taking in account that everything went smooth before the update it's something related to pipeline phase ...
    c
    a
    4 replies · 3 participants
  • m

    Michal Klimczak

    06/16/2021, 7:36 AM
    I have a problem with interrupted streaming in ktor and
    java.net.SocketException: Software caused connection abort
    (thread)
    r
    9 replies · 2 participants
  • r

    Rak

    06/16/2021, 11:06 AM
    I have setup ktor with json serialization and it works well. I can issue a request like this:
    val customer: Customer = client.get("<http://127.0.0.1:8080/customer>")
    My question is how can I then get the response headers?
    r
    1 reply · 2 participants
  • n

    natario1

    06/16/2021, 11:07 AM
    👋 is there any way to change the response headers? Server is not sending
    WWW-Authenticate
    on 401, so the Auth plugin is not working properly. I have tried with:
    client.receivePipeline.intercept(HttpReceivePipeline.Before) { response ->
        if (response.status == HttpStatusCode.Unauthorized && !response.headers.contains(HttpHeaders.WWWAuthenticate)) {
            val headers = buildHeaders {
                appendAll(response.headers)
                append(HttpHeaders.WWWAuthenticate, "Bearer")
            }
            proceedWith(object : HttpResponse() {
                override val headers get() = headers
                // delegate all other properties to original response
            })
        } else {
            proceed()
        }
    }
    And I can see with the debugger that this is invoked before the header check in Ktor's
    Auth
    class. But still, the response passed to Auth does not include my header. It seems like the response passed to
    proceedWith()
    does not replace
    call.response
    , which is what Auth plugin reads. Any idea?
    r
    a
    6 replies · 3 participants
  • j

    Jgafner

    06/16/2021, 12:51 PM
    Hi a small suggestion for the self certificate gradle task I think the
    generateJks
    task in the docs can be improve by setting the output of the task: I did something like this:
    tasks.register("generateJks", JavaExec::class) {
        dependsOn("classes")
        group = "certificate"
        classpath = sourceSets["main"].runtimeClasspath
        outputs.dir("${project.buildDir}/certs/")
    mainClass.set("com.my.main.Class")
    }
    and changed the object and the conf file:
    val jksFile = File("build/certs/temporary.jks").apply {
                parentFile.mkdirs()
            }
    a
    1 reply · 2 participants
  • n

    natario1

    06/16/2021, 2:17 PM
    What's the correct way to make a network request inside
    bearer.refreshTokens { }
    when using the Auth plugin? I'm trying to hit server from there using the same client that initiated the failed request, but I get a deadlock with both requests stuck. If I use a different
    HttpClient
    only inside
    refreshTokens { }
    , everything works fine 😕
    r
    4 replies · 2 participants
  • e

    elye

    06/17/2021, 2:49 PM
    Hi, just a quick check to understand ktor… for Ktor, when we use for Android, underlying it is using OkHttp. For iOS, what is it using? Alamofire? Thanks 🙏
    👇 1
    🇳🇴 1
    t
    a
    3 replies · 3 participants
  • a

    Andrew Steinmetz

    06/19/2021, 5:45 PM
    I am curious, has anybody used ktor as replacement for a mock web server in both Android and iOS automation? I know there is a MockEngine, but that only seems useful if all client requests are being made with a Ktor client and unfortunately my app is not fully converted over yet. So was curious if anybody has tried that or if its even a good use case for ktor?
    m
    d
    4 replies · 3 participants
  • t

    Tim Malseed

    06/20/2021, 12:34 PM
    Hey all, hopefully a simple one... (Edit: Solved) I'm trying to read a file:
    File("./srv/emails.txt")
    The file is located at
    project_root/srv/emails.txt
    . But I get a
    FileNotFoundException
    when I call
    readLines
    on the file
    2 replies · 1 participant
  • d

    darkmoon_uk

    06/20/2021, 12:59 PM
    Is there currently a way to use Ktor and Flows together; so that an HTTP request could be responded to by a
    Flow
    of (serialized) objects i.e. delivered by HTTP streaming?
    👀 4
    1 reply · 1 participant
  • v

    Voronin Sergey

    06/21/2021, 8:57 AM
    Hi! Can u help me? I use ContentConverter for get files over Graphql. Can i convert input ByteReadChannel to PartData using default tooling? Now i use CIOMultipartDataBase for it, but he have @InternalAPI annotation. How i can do right?
    a
    3 replies · 2 participants
  • s

    Sourabh Rawat

    06/22/2021, 10:55 AM
    Hi, does anyone have some ktor project links of medium-large size, possibly production ready? Looking for learning. Thanks in advance.
    b
    2 replies · 2 participants
  • a

    Aleksandr Ivanov

    06/24/2021, 6:55 AM
    Trying to migrate from ktor 1.5.3 to 1.6.0 in my multiplatform project, but got a freeze exception, when initialise HttpClient. I found that there is already known issue with HashMaps (https://github.com/Kotlin/kotlinx.serialization/issues/1450) but looks like it is not my case. There is my stack trace:
    Uncaught Kotlin exception: kotlin.native.concurrent.InvalidMutabilityException: mutation attempt of frozen kotlinx.coroutines.JobImpl@2516528
        at 0   DriversAppApi                       0x000000010155103f kfun:kotlin.Throwable#<init>(kotlin.String?){} + 95 (/Users/teamcity3/buildAgent/work/290aee0e088a1666/runtime/src/main/kotlin/kotlin/Throwable.kt:23:37)
        at 1   DriversAppApi                       0x00000001015497ad kfun:kotlin.Exception#<init>(kotlin.String?){} + 93 (/Users/teamcity3/buildAgent/work/290aee0e088a1666/runtime/src/main/kotlin/kotlin/Exceptions.kt:23:44)
        at 2   DriversAppApi                       0x0000000101549a1d kfun:kotlin.RuntimeException#<init>(kotlin.String?){} + 93 (/Users/teamcity3/buildAgent/work/290aee0e088a1666/runtime/src/main/kotlin/kotlin/Exceptions.kt:34:44)
        at 3   DriversAppApi                       0x00000001015819fd kfun:kotlin.native.concurrent.InvalidMutabilityException#<init>(kotlin.String){} + 93 (/Users/teamcity3/buildAgent/work/290aee0e088a1666/runtime/src/main/kotlin/kotlin/native/concurrent/Freezing.kt:22:60)
        at 4   DriversAppApi                       0x0000000101581dcf ThrowInvalidMutabilityException + 431 (/Users/teamcity3/buildAgent/work/290aee0e088a1666/runtime/src/main/kotlin/kotlin/native/concurrent/Internal.kt:93:11)
        at 5   DriversAppApi                       0x00000001016e5b50 MutationCheck + 128
        at 6   DriversAppApi                       0x00000001017ebda6 kfun:kotlinx.coroutines.JobImpl#<init>(kotlinx.coroutines.Job?){} + 150 (/opt/buildAgent/work/44ec6e850d5c63f0/kotlinx-coroutines-core/common/src/JobSupport.kt:1328:46)
        at 7   DriversAppApi                       0x00000001017d692c kfun:kotlinx.coroutines#Job(kotlinx.coroutines.Job?){}kotlinx.coroutines.CompletableJob + 188 (/opt/buildAgent/work/44ec6e850d5c63f0/kotlinx-coroutines-core/common/src/Job.kt:379:55)
        at 8   DriversAppApi                       0x00000001019f9254 kfun:io.ktor.client.HttpClient#<init>(io.ktor.client.engine.HttpClientEngine;io.ktor.client.HttpClientConfig<out|io.ktor.client.engine.HttpClientEngineConfig>){} + 1796 (/Users/administrator/Documents/agent/work/8d547b974a7be21f/ktor-client/ktor-client-core/common/src/io/ktor/client/HttpClient.kt:87:45)
        at 9   DriversAppApi                       0x00000001019fa310 kfun:io.ktor.client.HttpClient#<init>(io.ktor.client.engine.HttpClientEngine;io.ktor.client.HttpClientConfig<out|io.ktor.client.engine.HttpClientEngineConfig>;kotlin.Boolean){} + 144 (/Users/administrator/Documents/agent/work/8d547b974a7be21f/ktor-client/ktor-client-core/common/src/io/ktor/client/HttpClient.kt:81:9)
        at 10  DriversAppApi                       0x00000001019f8ad5 kfun:io.ktor.client#HttpClient(io.ktor.client.engine.HttpClientEngine;kotlin.Function1<io.ktor.client.HttpClientConfig<*>,kotlin.Unit>){}io.ktor.client.HttpClient + 517 (/Users/administrator/Documents/agent/work/8d547b974a7be21f/ktor-client/ktor-client-core/common/src/io/ktor/client/HttpClient.kt:62:17)
        at 11  DriversAppApi                       0x00000001011b389d kfun:com.arrival.adp.drivers.app.api.rest.HttpClientFactory#create(){}io.ktor.client.HttpClient + 285 (/Users/alexander.ivanov/Development/pmob-sdrv-graphql-api-tool/sources/drivers-app-api/src/commonMain/kotlin/com/arrival/adp/drivers/app/api/rest/HttpClientFactory.kt:31:16)
    My version changes: kotlin:
    1.4.32
    ->
    1.5.10
    Ktor:
    1.5.3
    ->
    1.6.0
    kotlinx.coroutines:
    1.4.3-native-mt
    ->
    1.5.0-native-mt
    kotlinx.serialization:
    1.1.0
    ->
    1.2.1
    Does somebody faced this issue?
    a
    m
    9 replies · 3 participants
  • a

    Ankit Dubey

    06/24/2021, 7:02 AM
    Hi, while calling ktor API, if my query is of different type, I’m getting below exception java.lang.IllegalStateException: Serializing collections of different element types is not yet supported. Selected serializers: [kotlin.String, kotlin.Int]
    val query = hashMapOf<String,Any>(
        KEY_OTP to otp.toInt(),
        KEY_MOBILE to phone
    )
    This is what I’ve posted However I achieved the excepted result by sending a model class as
    @Serializable
    data class OTPRequest(
        val mobile : String,
        val otp : Int
    )
    But I was wondering, It’ll be a extra burden if I’m going to create multiple request classes Any solution will be helpful. thanks
    r
    2 replies · 2 participants
  • j

    jean

    06/24/2021, 7:50 AM
    Is it possible to install a feature dynamically? I’m looking into integrating a login feature through through an OAuth provider stating in its doc that endpoints should be fetch and not stored statically since they could (rarely) change over time. From what I see in the doc from Ktor, the OAuth configuration is done directly into the Application block and it’s static
    a
    2 replies · 2 participants
  • s

    Sean Abbott

    06/24/2021, 2:10 PM
    Hello, I'm trying to get call logging to work with my new ktor application. Is the logback line ABSOLUTELY necessary? My more-java-and-kotlin-experienced coworkers don't want to add logback into our dependencies they want everything to go through slf4j, so right now I'm not getting any trace prints about calls that the server receives. So far I'm just using the netty engine. I followed the tutorial, and (simplified) I have:
    fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)
    
    fun Application.module(testing: Boolean = false) {
        install(ContentNegotiation) {
            json()
        }
        install(CallLogging)
        registerAccountRoutes()
        registerHealthRoutes()
    }
    The install ContentNegotiation works, but CallLogging isn't doing anything as far as I can tell.
    1 reply · 1 participant
  • s

    Sean Abbott

    06/24/2021, 6:28 PM
    What's the best way to use coroutines to launch work and then respond without waiting for the work to finish? Basically, I want to accept a request, validate it, launch work, and then respond that it was a valid request and work is being done. I don't need to have a callback for this. So like (pseodo-kotlin-ish)
    route("/foo") {
      get("{bar}") {
        if not validFoo(call.parameters) return@get call.respondText("invalid", status = HttpStatusCode.BadRequest)
        launch { longRunningWorkIDontNeedAResponseFrom(call.parameters) }
        call.respondText("Started work")
      }
    }
    I know I'm using coroutine already, but...do I need to set up the coroutine scope? Can I share a thread pool with ktor?
    b
    4 replies · 2 participants
  • j

    jean

    06/25/2021, 8:30 AM
    I’m trying to publish my ktor app through docker by following this doc https://ktor.io/docs/docker.html#building-and-running-the-docker-image. When running
    docker build -t my-app .
    I’m getting this error message :
    => ERROR [3/4] COPY ./build/install/docker/ /app/                                                                                                                                             
    ------
     > [3/4] COPY ./build/install/docker/ /app/:
    ------
    failed to compute cache key: "/build/install/docker" not found: not found
    What am I doing wrong here?
    a
    7 replies · 2 participants
  • h

    Himanshu Singh

    06/26/2021, 11:26 AM
    There is a very weird issue coming up. I have all the plugins installed once. But when I try to run the project I get
    Exception in thread "main" io.ktor.application.DuplicateApplicationFeatureException: Conflicting application feature is already installed with the same key as `CORS`
    And the code looks like:
    fun main() {
        embeddedServer(Netty, port = 8081, host = "0.0.0.0") {
            configureHTTP()
            configureOauth()
            configureRoutingAndSerialization()
            configureStatusPages()
        }.start(wait = true)
    }
    The weird part is: The first feature which is inside the blocks always throws the error. In this case is HTTP but if I take Oauth to first position it will throw exception of
    Authentication
    a
    1 reply · 2 participants
  • n

    Nikolay Kasyanov

    06/26/2021, 12:26 PM
    Hey folks, heads up, SSL pinning implementation crashes on iOS 11 because it uses SecCertificateCopyKey that’s only available starting iOS 12.
    a
    4 replies · 2 participants
  • m

    maskipli

    06/27/2021, 4:46 AM
    hey folks. how to mapping result from Ktor request into sealed class like bellow
    sealed class NetworkResponse<out S : Any, out E : Any> {
    
        data class Success<S : Any>(
            val body: S,
            val code: Int
        ) : NetworkResponse<S, Nothing>()
    
        data class Error<E : Any>(
            val errorBody: E,
            val code: Int
        ) : NetworkResponse<Nothing, E>()
    
        data class Failure(val error: Exception) : NetworkResponse<Nothing, Nothing>()
    
    }
    e
    4 replies · 2 participants
  • s

    Stewart Matheson

    06/28/2021, 10:55 PM
    Hi Everyone! After years using mac and Linux I have stepped in to a new role with a windows box. Have not used windows in years! It's been nice in some places. Windows Terminal has been good and powershell looks really interesting(not that I was not able to use it before). I will be using ktor for the first time too. I was wondering if anyone had any luck building from source on windows? Works on Windows Subsystem for Linux however in windows there are some platform deps in utils io that require posix. Have I missed something to setup the build for native windows or is this not supported at this stage? If not supported is there some work that could be done to support native windows or is too much built around posix API's?
    b
    m
    17 replies · 3 participants
Powered by Linen
Title
s

Stewart Matheson

06/28/2021, 10:55 PM
Hi Everyone! After years using mac and Linux I have stepped in to a new role with a windows box. Have not used windows in years! It's been nice in some places. Windows Terminal has been good and powershell looks really interesting(not that I was not able to use it before). I will be using ktor for the first time too. I was wondering if anyone had any luck building from source on windows? Works on Windows Subsystem for Linux however in windows there are some platform deps in utils io that require posix. Have I missed something to setup the build for native windows or is this not supported at this stage? If not supported is there some work that could be done to support native windows or is too much built around posix API's?
b

Big Chungus

06/28/2021, 11:06 PM
You need cygwin or msys2 with posix libs installed i think
👍 2
Basically build on mingw, rather than plain old windows
👍 2
s

Stewart Matheson

06/28/2021, 11:15 PM
Thanks @Big Chungus I have never used either so I will check them out. WSL is working ok but there are file sharing issues between the host and linux. Will have a look at these today as it looks like they don't require an emulation layer
m

msink

06/29/2021, 5:02 AM
AFAIK from WSL Kotlin builds Linux apps, not native Windows. If you want posix shell - install MSYS2 and run in their shell. And in it -
pacman
as package manager. As for examples - https://github.com/msink/hello-curl builds static app for both 32 and 64 bit native Windows, locally and on GitHub CI.
In fact K/N Windows sysroot itself is built from MSYS2, so compatibility with anything built or installed from MSYS2 shell is maximal.
s

Stewart Matheson

06/29/2021, 5:45 AM
Hey Mike, Thanks for the reply. I have downloaded and installed MSYS2. I get the same result there as I get in cygwin as I get in native powershell which is as follows.
e: C:\Users\StewartMatheson\Documents\NotInventedHere\ktor\ktor-io\posix\src\io\ktor\utils\io\errors\PosixErrors.kt: (11, 30): Cannot access class 'platform.posix.SOCKET'. Check your module classpath for missing or conflicting dependencies
e: C:\Users\StewartMatheson\Documents\NotInventedHere\ktor\ktor-io\posix\src\io\ktor\utils\io\streams\PosixIo.kt: (78, 27): Cannot access class 'platform.posix.SOCKET'. Check your module classpath for missing or conflicting dependencies
e: C:\Users\StewartMatheson\Documents\NotInventedHere\ktor\ktor-io\posix\src\io\ktor\utils\io\streams\PosixIo.kt: (78, 27): Type mismatch: inferred type is KX_SOCKET /* = SOCKET */ but Int was expected
e: C:\Users\StewartMatheson\Documents\NotInventedHere\ktor\ktor-io\posix\src\io\ktor\utils\io\streams\PosixIo.kt: (93, 17): Cannot access class 'platform.posix.SOCKET'. Check your module classpath for missing or conflicting dependencies
e: C:\Users\StewartMatheson\Documents\NotInventedHere\ktor\ktor-io\posix\src\io\ktor\utils\io\streams\PosixIo.kt: (93, 17): Type mismatch: inferred type is KX_SOCKET /* = SOCKET */ but Int was expected
e: C:\Users\StewartMatheson\Documents\NotInventedHere\ktor\ktor-io\posix\src\io\ktor\utils\io\streams\PosixIo.kt: (98, 12): Cannot access class 'platform.posix.SOCKET'. Check your module classpath for missing or conflicting dependencies
e: C:\Users\StewartMatheson\Documents\NotInventedHere\ktor\ktor-io\posix\src\io\ktor\utils\io\streams\PosixIo.kt: (98, 17): Cannot access class 'platform.posix.SOCKET'. Check your module classpath for missing or conflicting dependencies
e: C:\Users\StewartMatheson\Documents\NotInventedHere\ktor\ktor-io\posix\src\io\ktor\utils\io\streams\PosixIo.kt: (174, 27): Cannot access class 'platform.posix.SOCKET'. Check your module classpath for missing or conflicting dependencies
e: C:\Users\StewartMatheson\Documents\NotInventedHere\ktor\ktor-io\posix\src\io\ktor\utils\io\streams\PosixIo.kt: (174, 27): Type mismatch: inferred type is KX_SOCKET /* = SOCKET */ but Int was expected
e: C:\Users\StewartMatheson\Documents\NotInventedHere\ktor\ktor-io\posix\src\io\ktor\utils\io\streams\PosixIo.kt: (196, 31): Cannot access class 'platform.posix.SOCKET'. Check your module classpath for missing or conflicting dependencies
e: C:\Users\StewartMatheson\Documents\NotInventedHere\ktor\ktor-io\posix\src\io\ktor\utils\io\streams\PosixIo.kt: (196, 31): Type mismatch: inferred type is KX_SOCKET /* = SOCKET */ but Int was expected
e: C:\Users\StewartMatheson\Documents\NotInventedHere\ktor\ktor-io\posix\src\io\ktor\utils\io\streams\PosixIo.kt: (196, 94): Type mismatch: inferred type is CValuesRef<IntVarOf<KX_SOCKADDR_LEN /* = Int */>> but CValuesRef<socklen_tVar /* = UIntVarOf<UInt> */>? was expected
e: C:\Users\StewartMatheson\Documents\NotInventedHere\ktor\ktor-io\posix\src\io\ktor\utils\io\streams\PosixIo.kt: (218, 29): Cannot access class 'platform.posix.SOCKET'. Check your module classpath for missing or conflicting dependencies
e: C:\Users\StewartMatheson\Documents\NotInventedHere\ktor\ktor-io\posix\src\io\ktor\utils\io\streams\PosixIo.kt: (218, 29): Type mismatch: inferred type is KX_SOCKET /* = SOCKET */ but Int was expected
e: C:\Users\StewartMatheson\Documents\NotInventedHere\ktor\ktor-io\posix\src\io\ktor\utils\io\streams\PosixIo.kt: (218, 91): Type mismatch: inferred type is KX_SOCKADDR_LEN /* = Int */ but socklen_t /* = UInt */ was expected
I tried building your hello-curl repo too
I get the following
> Task :cinteropLibcurlMingw32 FAILED
Exception in thread "main" java.lang.Error: C:\Users\STEWAR~1\AppData\Local\Temp\1473305343316438614.c:1:10: fatal error: 'curl/curl.h' file not found
        at org.jetbrains.kotlin.native.interop.indexer.UtilsKt.ensureNoCompileErrors(Utils.kt:152)
        at org.jetbrains.kotlin.native.interop.indexer.IndexerKt.indexDeclarations(Indexer.kt:1003)
        at org.jetbrains.kotlin.native.interop.indexer.IndexerKt.buildNativeIndexImpl(Indexer.kt:992)
        at org.jetbrains.kotlin.native.interop.indexer.NativeIndexKt.buildNativeIndex(NativeIndex.kt:91)
        at org.jetbrains.kotlin.native.interop.gen.jvm.MainKt.processCLib(main.kt:268)
        at org.jetbrains.kotlin.native.interop.gen.jvm.MainKt.interop(main.kt:76)
        at org.jetbrains.kotlin.cli.utilities.InteropCompilerKt.invokeInterop(InteropCompiler.kt:45)
        at org.jetbrains.kotlin.cli.utilities.MainKt.mainImpl(main.kt:38)
        at org.jetbrains.kotlin.cli.utilities.MainKt.main(main.kt:60)
So I'm wondering if there is some extra paths I have to setup perhaps.
m

msink

06/29/2021, 5:59 AM
Did you install mingw-w64-x86_64-curl and mingw-w64-i686-curl?
pacman -S mingw-w64-x86_64-curl mingw-w64-i686-curl
in MSYS2 shell.
And you need to add -L parameter to them in your linkerOpts.
includeDirs too
s

Stewart Matheson

06/29/2021, 10:41 PM
Hey @msink installing the two packages got the hello curl example compiling. Thanks. I did not have to tell the compiler about any extra paths either. Issue persists with ktor though. I will dig a little deeper today. At this point I suspect its something to do with c interop not binding correctly as the classes that are erroring are all as I understand provided by a
.def
file in kotlin native. Perhaps the cinterops are not even running. This might happen if
nativeTargets
in
build.gradle.kts
in the ktor-io project is not set. I will start debugging that today. Any other suggests are more than welcome.
nativeTargets.forEach {
        it.compilations {
            val main by getting {
                cinterops {
                    val bits by creating { defFile = file("posix/interop/bits.def") }
                    val sockets by creating { defFile = file("posix/interop/sockets.def") }
                }
            }
            val test by getting {
                cinterops {
                    val testSockets by creating { defFile = file("posix/interop/testSockets.def") }
                }
            }
        }
    }
m

msink

06/30/2021, 12:20 PM
Seems that building Ktor on windows is just broken.
Cloned from github, on
main
and
1.6.0
- build failed with exactly same errors, on tag
1.5.4
- build passed.
Wonder how
1.6.0
for windows was published...
Well, I was wrong
:ktor-io:compilePosixMainKotlinMetadata
failed on
1.5.4
too, but after 30 minutes of various tests.
View count: 4