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
  • h

    hhariri

    05/31/2020, 12:29 PM
    New Twitter account where we’ll be posting news, tips, etc. https://twitter.com/JetBrainsKtor
    👍 16
    e
    • 2
    • 2
  • a

    aleksey.tomin

    06/01/2020, 1:02 PM
    How can I serialize class with set of class by
    kotlinx-serialization
    in 1.3.0? I have
    kotlinx.serialization.SerializationException: Can't locate argument-less serializer for class DeviceItems
    All examples for older versions
    @Serializable
    data class DeviceItems(val id: String, val rows: Set<DeviceItem>)
    s
    t
    • 3
    • 9
  • a

    Aaron Todd

    06/01/2020, 1:41 PM
    Is there anyway to be notified when a
    ByteReadChannel
    has been exhausted (or closed)?
    e
    • 2
    • 5
  • m

    Michael Burbidge

    06/01/2020, 2:55 PM
    Posting this question again, hoping someone will notice and answer: I’m working with push based HTTP API that uses chunked transfer encoding to push messages. I need access to the individual HTTP chunks while reading the response. Is there a way using the ktor HttpClient to get access to the HTTP Chunks?
    e
    e
    • 3
    • 10
  • t

    Thiyagu

    06/01/2020, 6:29 PM
    Do anyone tried multiple configuration something like environment based configuration which spring boot provides???
    b
    m
    • 3
    • 4
  • h

    hhariri

    06/02/2020, 10:22 AM
    Folks, we’re looking for case studies / testimonials for Ktor. If you’re using it in production and are open to discuss your usage, please ping me. Thanks.
    👀 4
    c
    s
    • 3
    • 2
  • s

    spand

    06/02/2020, 12:39 PM
    Can I direct some attention to https://github.com/ktorio/ktor/issues/1266 . Doing without this feature is really problematic
    h
    • 2
    • 3
  • a

    addamsson

    06/02/2020, 1:48 PM
    Hi there! I have a question about Ktor. Was it intended as a techdemo only? I've read on reddit that some people think that it was not meant for production use. Is this true?
    🇳🇴 7
    d
    t
    +2
    • 5
    • 25
  • t

    Thiyagu

    06/02/2020, 6:35 PM
    I would like like to create a routes in programatic way instead of using dsl. Is there any sample available on this?
    c
    h
    • 3
    • 5
  • a

    andev

    06/02/2020, 8:20 PM
    Hi, my app is acting like a proxy between the client app and server. A client makes a request, if cached data is valid i.e. not expired, I serve him that, otherwise I make a request to the server, get data, cache it, and then serve it to the client. I wrote some code, but it's not thread-safe. How can I improve this so I do not make unnecessary requests to the server?
    fun Application.module() {
        val client = HttpClient(OkHttp) {
            install(JsonFeature) {
                serializer = GsonSerializer()
            }
        }
        var cached: Data? = null
        routing {
            get("/") {
                if (cached == null) {
                    val new = client.get<Data>("<https://my-host.com/message>")
                    cached = new
                }
                if (cached!!.expires < System.currentTimeMillis()) {
                    val new = client.get<Data>("<https://my-host.com/message>")
                    cached = new
                }
                call.respond(cached!!.message)
            }
        }
    }
    
    data class Data(val expires: Long, val message: String)
    r
    • 2
    • 2
  • j

    Jolas

    06/03/2020, 3:50 AM
    Hi guys, I have a kotlin multiplatform project that is used as a module in iOS app and Android app to act as Data Repository. I am trying to implement a method to upload files in this KMP Module that can be accessed from iOS app code and Android App Code. Is there any documented way or some blog posts that help this scenario?
    e
    • 2
    • 1
  • t

    tim

    06/03/2020, 9:21 AM
    Good day, I'm struggling to set
    cookie.secure = true
    as my server is throwing. I've been trying to work through this to no success. Here's the top of the stacktrace:
    10:15:06.019 [ktor-jetty-10001-1] ERROR Application - 500 Internal Server Error: GET - /cloud/v1/vault
    java.lang.IllegalArgumentException: You should set secure cookie only via secure transport (HTTPS)
    	at io.ktor.response.ResponseCookies.append(ResponseCookies.kt:30)
    	at io.ktor.sessions.SessionTransportCookie.send(SessionTransportCookie.kt:52)
    	at io.ktor.sessions.SessionsKt.sendSessionData(Sessions.kt:214)
    	at io.ktor.sessions.Sessions$Feature$install$2.invokeSuspend(Sessions.kt:76)
    	at io.ktor.sessions.Sessions$Feature$install$2.invoke(Sessions.kt)
    	at io.ktor.util.pipeline.SuspendFunctionGun.loop(PipelineContext.kt:318)
    	at io.ktor.util.pipeline.SuspendFunctionGun.proceed(PipelineContext.kt:163)
    	at io.ktor.util.pipeline.SuspendFunctionGun.execute(PipelineContext.kt:183)
    	at io.ktor.util.pipeline.Pipeline.execute(Pipeline.kt:27)
    I'm running my ktor behind an nginx proxy which terminates https and passes the request on via reverse proxy to the ktor server. Nginx is forwarding these X-Forwarded headers:
    "X-Forwarded-For": "[omitted]",
      "X-Forwarded-Proto": "[https]",
    And nginx conf block:
    location /cloud/v1 {
      proxy_set_header X-Forwarded-For $remote_addr;
      proxy_set_header X-Forwarded_Proto 'https';
      proxy_pass <http://127.0.0.1:10001>;
    }
    In my ktor server setup i have:
    install(XForwardedHeaderSupport)
    As far as I have read, this should now be working but I am still getting the error. I have logged out
    call.request.origin.scheme
    inside one of my controllers and its returning
    http
    so it appears that the XForwadedHeaderSupport isn't setting the scheme to
    https
    ... any suggestions?! 🙏
    s
    • 2
    • 4
  • r

    rudolf.hladik

    06/04/2020, 11:49 AM
    Kotlin 1.4 M2 released, Ktor support for native-mt coroutines Coming soon™️
    🎉 8
    e
    a
    +2
    • 5
    • 10
  • a

    andev

    06/07/2020, 9:15 AM
    Guys, i wanted to build Ktor from the source, but the IDEA isn't helpful at all. Like, it doesn't even register that there is a gradle build script there.. so it doesn't even know that this is a gradle project. What's your experience with building Ktor from source? Any advice?
    • 1
    • 1
  • e

    edwinRNDR

    06/07/2020, 8:15 PM
    this seems related: https://github.com/Kotlin/kotlinx.html/issues/147
    m
    h
    • 3
    • 3
  • h

    Hamza

    06/08/2020, 2:21 PM
    https://api.ktor.io/1.3.2/io.ktor.client.statement/read-text.html How come this responds with an error if the response code is not 200?
    HttpClient().use { client ->
     val response = client.submitForm<HttpResponse>(
      url = "<https://discord.com/api/oauth2/token>",
      formParameters = Parameters.build {
       append("client_id", config.discord.client)
       append("client_secret", config.discord.secret)
       append("grant_type", "authorization_code")
       append("redirect_uri", config.discord.redirect)
       append("scope", "identify")
       append("code", code)
      })
      println(response.readText()) // throws an error if response status is not 200.
    }
    a
    • 2
    • 4
  • a

    Archie

    06/08/2020, 2:56 PM
    Hi guys, I have a Ktor
    HttpClient
    set like so:
    HttpClient(engine) {
        defaultRequest {
            header("A Header", headerValue)
        }
    }
    I wanted to add a test to that ensures that everytime I make a request to the
    HttpClient
    it would add the stated header. Is there a way to do this test?
    h
    a
    +3
    • 6
    • 11
  • a

    Anders Sveen

    06/09/2020, 5:11 PM
    Hi guys. Curious as to how you handle async in KTor server. We have withContext(Dispatchers.IO) {...} on the slowest calls but not everything. Do you do async on everything? I suspect some requests on our end are "slow" because of queuing requests. Is there some way to log/analyse queue length? I can't find anything that lets me tap into that as a metric...
    m
    g
    • 3
    • 16
  • a

    Archie

    06/10/2020, 11:43 AM
    Anyone having
    DoubleReceiveException
    issue? How did you work around this?
    a
    • 2
    • 1
  • p

    Philipp Mayer

    06/10/2020, 12:38 PM
    Hello guys, I need some help regarding the usage of the application.conf file. I have a service which reads his configuration from application.conf:
    class MqttHandler : SensorExchangeUseCase {
        /**
         *  Factory to read the application.conf file
         *  <https://stackoverflow.com/questions/53891189/how-do-i-use-custom-configuration-in-ktor>
         */
        private val config: MqttConfig = with(ConfigFactory.load()) {
            MqttConfig(
                this.getString("mqtt.topic"),
                getString("mqtt.brokerUrl"),
                getInt("mqtt.port"),
                getString("mqtt.clientId")
            )
        }
    To test that, I created the following test:
    class MqttHandlerTest : FunSpec({
        withTestApplication {
            (environment.config as MapApplicationConfig).apply {
                put("mqtt.topic", "karlheinz")
                put("mqtt.brokerUrl", container.host)
                put("mqtt.port", port.toString())
                put("mqtt.clientId", "Karl")
            }
            main()
        }
    
    
        test("should read correct Config from HOCON File") {
            with(ConfigFactory.load()) {
                getString("mqtt.topic") shouldBe "karlheinz"
                getString("mqtt.brokerUrl") shouldBe container.host
                getInt("mqtt.port") shouldBe port
                getString("mqtt.clientId") shouldBe "Karl"
            }
        }
    However, my test fails since it loads the values which are in my local file and not the values that I put there with
    withTestApplication
    . My Service is not an application module. How could I test the behaviour? It feels like I'm missing something. Thanks in advance!
    m
    • 2
    • 4
  • j

    jean

    06/10/2020, 6:44 PM
    After a quick search on this channel and the web, it looks like to me there is no convenient way of setting a base url value? I saw people suggested to use this
    HttpClient(CIO) {
            defaultRequest {
                url {
                    host = "<https://my.host.com>"
                    port = 443
                }
            }
            install(JsonFeature) {
                serializer = GsonSerializer()
            }
        }
    I does not work when I try to use it with
    client.get<ApiResponse<Character>>("/endpoint")
    Am I doing anything wrong?
    n
    • 2
    • 4
  • e

    e5l

    06/11/2020, 8:41 AM
    📣 Ktor
    1.3.2-1.4-M2
    has been released with Kotlin 1.4-M2 support
    🍾 3
    👍 12
    j
    z
    +3
    • 6
    • 14
  • s

    Sean Keane

    06/11/2020, 4:07 PM
    Hi All, I'm trying to configure a server to use
    build.gradle.kts
    instead of
    build.gradle
    . When I configure it from the wizard and build it works fine out of the box. When I convert the file I get the following error.
    INFO  Application - No ktor.deployment.watch patterns specified, automatic reload is not active
    Exception in thread "DefaultDispatcher-worker-3" java.lang.ClassNotFoundException: Module function cannot be found for the fully qualified name 'com.example.ApplicationKt.module'
    This is my
    build.gradle.kts
    file
    buildscript {
        repositories {
            jcenter()
            mavenCentral()
            maven{
                url = uri("<https://kotlin.bintray.com/ktor>")
                url = uri("<https://kotlin.bintray.com/kotlinx>")
            }
        }
        
        dependencies {
            classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.72")
        }
    }
    
    //Setup the application plugins
    plugins {
        application
        kotlin("jvm") version "1.3.72"
    }
    
    group = "com.example"
    version = "0.0.1"
    
    application {
        mainClassName = "io.ktor.server.cio.EngineMain"
    }
    
    sourceSets["main"].resources.srcDirs("resources")
    sourceSets["test"].resources.srcDirs("testresources")
    
    repositories {
        mavenCentral()
        mavenLocal()
        jcenter()
        maven{
            url = uri("<https://kotlin.bintray.com/ktor>")
            url = uri("<https://kotlin.bintray.com/kotlinx>")
        }
    }
    
    dependencies {
        implementation(kotlin("stdlib-jdk8"))
        implementation("io.ktor:ktor-server-cio:1.3.2")
        implementation("ch.qos.logback:logback-classic:1.2.1")
        implementation("io.ktor:ktor-server-core:1.3.2")
        implementation("io.ktor:ktor-locations:1.3.2")
        implementation("io.ktor:ktor-metrics:1.3.2")
        implementation("io.ktor:ktor-client-core:1.3.2")
        implementation("io.ktor:ktor-client-core-jvm:1.3.2")
        implementation("io.ktor:ktor-client-cio:1.3.2")
        implementation("io.ktor:ktor-client-json-jvm:1.3.2")
        implementation("io.ktor:ktor-client-gson:1.3.2")
        implementation("io.ktor:ktor-client-logging-jvm:1.3.2")
        testImplementation("io.ktor:ktor-server-tests:1.3.2")
    }
    Im not really sure why its not picking it up.
    • 1
    • 2
  • a

    aleksey.tomin

    06/11/2020, 5:02 PM
    How can I add ktor-client-CIO to KN with “1.3.2-1.4-M2”? I try to create macosX64 compile 1. When I add dependencies
    ktor-client-core
    and
    ktor-http-cio
    I’ve had a error
    Could not find "io.ktor:ktor-io-cinterop-bits" in...
    2. When I add dependencies
    ktor-client-core
    and
    ktor-client-cio
    I’ve had a error
    No matching variant of io.ktor:ktor-client-cio:1.3.2-1.4-M2 was found
    3. When I add dependencies
    ktor-client-core
    and
    ktor-client-cio-kotlinMultiplatform
    I’ve had a error
    Could not find "io.ktor:ktor-io-cinterop-bits" in...
    How can I do it?
    r
    • 2
    • 2
  • c

    CLOVIS

    06/12/2020, 12:59 PM
    Hi, I found how to use `FileReader`etc to upload an image with multipart requests, but I don't understand how I can unit test it. I'm searching for a way to get access to a JS
    File
    or
    Blob
    from a URL (it's a PNG image). I found the example that shows how to do this with Kotlin/JVM, but nothing for Kotlin/JS at the moment. Is it possible?
    s
    • 2
    • 4
  • a

    addamsson

    06/13/2020, 7:14 PM
    Hi there! Do any of you know how can I use
    call.receiveParameters()
    when I use the content negotiation module? I get
    kotlinx.serialization.SerializationException: Can't locate argument-less serializer for class Parameters. For generic classes, such as lists, please provide serializer explicitly.
    How do I provide a serializer for Parameters? Or a Map? I'm using the kotlinx.serialization serializer like this:
    import io.ktor.application.Application
    import io.ktor.application.install
    import io.ktor.features.ContentNegotiation
    import io.ktor.serialization.json
    
    fun Application.configureContentNegotiation() {
        install(ContentNegotiation) {
            json()
        }
    }
    I also checked the docs but I did not find any examples for this.
    t
    • 2
    • 2
  • w

    waghanza

    06/14/2020, 8:52 AM
    Hi, I have no
    kotlin
    skills, but I am trying to add it (in fact upgrade to 1.3) in https://github.com/the-benchmarker/web-frameworks/pull/2951 Could someone help me ? I have some messages
    Class 'kotlin.Unit' is compiled by a pre-release version of Kotlin and cannot be loaded by this version of the compiler
    on
    gradle
    6.5 and
    kotlin
    1.3.72
    r
    n
    e
    • 4
    • 9
  • g

    GurpreetSK

    06/14/2020, 1:31 PM
    Hey everyone, I’m getting the following error while trying to test my repository logic
    Cannot access '<http://java.io|java.io>.Closeable' which is a supertype of 'io.ktor.client.HttpClient'. Check your module classpath for missing or conflicting dependencies kotlin multiplatform
    Can someone help?
    m
    • 2
    • 4
  • e

    esdudnik

    06/15/2020, 2:09 PM
    Hi all. I am working on multiplatform project that using websocket protocol. Does ktor support now websocket on iOS? Want to move all network communication in common code and implement all websocket logic there using ktor.
    h
    • 2
    • 2
  • z

    zalewski.se

    06/15/2020, 3:40 PM
    Is there any know problem with memory leak in Ktor on iOS? 🤔 I’m running an app where I’m just polling api every 1 sec and memory on iOS emulator just keeps growing.
    👀 1
    n
    • 2
    • 1
Powered by Linen
Title
z

zalewski.se

06/15/2020, 3:40 PM
Is there any know problem with memory leak in Ktor on iOS? 🤔 I’m running an app where I’m just polling api every 1 sec and memory on iOS emulator just keeps growing.
👀 1
n

napperley

06/16/2020, 4:00 AM
Ktor Client also has memory leak issues with the linuxX64 target.
View count: 6