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

    Sourabh Rawat

    07/18/2021, 8:48 PM
    How does ktor serialize
    body
    , which is of type
    Any
    ? When I do something like this, it fails..
    @Serializable
    class Foo(val bar: String)
    
    @Test
    fun test() {
        val any: Any = Foo("asd")
        Json.encodeToString(any).also { println(it) }
    }
    a
    6 replies · 2 participants
  • c

    CLOVIS

    07/19/2021, 8:35 AM
    I'm using a reverse proxy to handle HTTPS, but now Ktor refuses to set the
    Secure
    flag on cookies. What is a working workaround?
    a
    1 reply · 2 participants
  • c

    csieflyman

    07/19/2021, 9:59 AM
    I implement two features A and B. B depends on A. I call environment.monitor.subscribe(ApplicationStopping) to do shutdown task in the feature install function respectively. But the shutdown order is A → B, not B → A because ktor call addLast(registration) in ApplicationEvents.subscribe() Does anyone has workaround?
    a
    2 replies · 2 participants
  • ł

    Łukasz Bednarczyk

    07/19/2021, 1:08 PM
    hi 🙂 why did you remove this issue from the next release?
    a
    2 replies · 2 participants
  • n

    nordiauwu

    07/20/2021, 8:14 PM
    Why is StringValuesBuilder marked as @InternalAPI? It's used in Headers#build which is a public API
    t
    n
    +1
    13 replies · 4 participants
  • f

    Fernando Avanzo

    07/21/2021, 11:22 PM
    hi, guys, someone knows how create a documentation of a ktor application using openapi-generator? Thanks for you help
    👀 1
    c
    3 replies · 2 participants
  • r

    Robert Jaros

    07/22/2021, 6:20 AM
    I'm getting error with Ktor 1.6.1 deserializing this JSON:
    kotlinx.serialization.json.internal.JsonDecodingException: Unexpected JSON token at offset 66: Unexpected 'null' value instead of string literal
    JSON input: {"id":1,"method":"/kv/routeNumberServiceManager0","params":["null","\"ENGLISH\""]}
    e
    7 replies · 2 participants
  • p

    Paul Woitaschek

    07/22/2021, 10:05 AM
    Is it possible to publish the watchosx64 dependency retroactively? There was a bug in the publishing of 1.6.1 and it’s currently blocking us because we can’t debug our watchos app.
    a
    e
    9 replies · 3 participants
  • j

    Jgafner

    07/22/2021, 12:57 PM
    Hi I see in the documentation for both Server and Client the gradle dependency is
    implementation
    and not
    testImplementation
    is it a mistake or this is how things work with ktor ? Thanks
    a
    d
    3 replies · 3 participants
  • c

    christophsturm

    07/22/2021, 12:59 PM
    is there a way to send a http request without accept header with ktor client? I need it in my test suite to check that its handled correctly
    a
    h
    3 replies · 3 participants
  • j

    Jgafner

    07/22/2021, 1:02 PM
    I just saw the jetbrains Endpoints plugins - do you know about any plans to add ktor to the supported frameworks? https://www.jetbrains.com/help/idea/endpoints-tool-window.html thanks
    d
    2 replies · 2 participants
  • c

    Carlos Santos

    07/23/2021, 8:21 AM
    Hi guys, I've been looking for this info in the internet but I couldn't find a clear answer. Let's say that I have an endpoint like: GET -> /ktor I want to create an interceptor and put it in the pipeline but only for that particular endpoint. I don't want to create an interceptor and then check the request path like in the docs. I was looking for "clean" solution like a plugin or something similar. I know that there's an interface named RootRouteSelector but I couldn't figured out how it works. Do you know if this is possible, and if so, can you point me to some docs/example. Thank you!
    👍 1
    a
    j
    +1
    15 replies · 4 participants
  • l

    Lg

    07/23/2021, 7:26 PM
    Hello, I’m creating a WebSocket client in ktor and I’m successfully streaming data from one path, however, I’ve not been successful in trying to configure the client to consume a second path’s stream for the same host. I’ve seen examples of configuring routing for a WebSocket server and am wondering if there’s a clearer way to configure mapping each path to its own handler
    val client = HttpClient {
        install(WebSockets)
    }
    
    client.webSocket(HttpMethod.Get, host, port, path) { … }
    a
    1 reply · 2 participants
  • b

    Bradford Canonigo

    07/23/2021, 10:51 PM
    Hi all, what are the difference between these 2 dependencies?
    implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:$serializationVersion"
    implementation "io.ktor:ktor-client-serialization:$ktorVersion"
    I believe both are serialization dependencies for kotlin, or both are kotlinx serializers.
    r
    1 reply · 2 participants
  • ł

    Łukasz Bednarczyk

    07/24/2021, 6:50 AM
    Hi! I have a question about OAuth - how many endpoints do I need? On docs, we can read that 2: first per start process, second per callback. But I can start the auth process by the callback endpoint. How can I block it?
    a
    1 reply · 2 participants
  • s

    subashz

    07/25/2021, 10:23 AM
    val createdAt = datetime("created_at").default(LocalDateTime.now())
    This auto adds the createdAt to the table. But how to forwards this as unix timestamp for the client side. Also, how to configure the time zone while using default
    a
    1 reply · 2 participants
  • s

    subashz

    07/25/2021, 10:38 AM
    Also what library do you guys use to get something like "2 days ago", "1 mins ago", "just a second ago" .. Something like these. Is there carbon like alternatives for ktor ?
    b
    1 reply · 2 participants
  • j

    Jgafner

    07/25/2021, 5:22 PM
    Hi Generic Q - when testing a server is a good practice to load a test conf ? or better keep 1 conf file ? Asking because in the example here it show how to load the main conf file
    a
    1 reply · 2 participants
  • c

    cptneko

    07/25/2021, 8:31 PM
    Hello everyone. I'm trying to develop my app using Freemarker templates. They cache the template file and edits aren't showing up so I googled and found cacheStorage = NullCacheStorage() should help. It still caches after setting it so not good. Then I looked at the docs found that I should be able to set templateUpdateDelayMilliseconds to 0 to disable caching. Also doesn't work. What do I need to do to disable template caching?
    ✅ 1
    1 reply · 1 participant
  • s

    smallufo

    07/27/2021, 9:56 AM
    Hi , I got tons of “ktor-client-apache” threads when running a server. And in fact the server is not doing anything . Is there anyway to find out where goes wrong ?
    jstack 45158 | grep Ktor-client-apache | wc -l                                                                                                                         
         125      // there are 125 threads generated !
    And the thread number starts from #19 to #144
    jstack 45158 | grep Ktor-client-apache
                                                                                                                                     
    "Ktor-client-apache" #19 daemon prio=5 os_prio=31 cpu=12.09ms elapsed=513.05s tid=0x0000000135bc4c00 nid=0x8403 runnable  [0x0000000172df2000]
    "Ktor-client-apache" #20 daemon prio=5 os_prio=31 cpu=11.36ms elapsed=513.05s tid=0x0000000144e30200 nid=0x7b03 runnable  [0x0000000172ffe000]
    ...
    ...
    "Ktor-client-apache" #143 daemon prio=5 os_prio=31 cpu=8.96ms elapsed=510.76s tid=0x0000000142a3d400 nid=0x1fe03 runnable  [0x0000000292bea000]
    "Ktor-client-apache" #144 daemon prio=5 os_prio=31 cpu=7.24ms elapsed=510.76s tid=0x0000000142a3ce00 nid=0x21903 runnable  [0x0000000292df6000]
    And I cannot figure out how it starts … :
    "Ktor-client-apache" #144 daemon prio=5 os_prio=31 cpu=8.90ms elapsed=591.80s tid=0x0000000142a3ce00 nid=0x21903 runnable  [0x0000000292df6000]
       java.lang.Thread.State: RUNNABLE
    	at sun.nio.ch.KQueue.poll(java.base@15.0.2/Native Method)
    	at sun.nio.ch.KQueueSelectorImpl.doSelect(java.base@15.0.2/KQueueSelectorImpl.java:122)
    	at sun.nio.ch.SelectorImpl.lockAndDoSelect(java.base@15.0.2/SelectorImpl.java:129)
    	- locked <0x00000006c6b79ec0> (a sun.nio.ch.Util$2)
    	- locked <0x00000006c6b79e68> (a sun.nio.ch.KQueueSelectorImpl)
    	at sun.nio.ch.SelectorImpl.select(java.base@15.0.2/SelectorImpl.java:141)
    	at org.apache.http.impl.nio.reactor.AbstractIOReactor.execute(AbstractIOReactor.java:255)
    	at org.apache.http.impl.nio.reactor.BaseIOReactor.execute(BaseIOReactor.java:104)
    	at org.apache.http.impl.nio.reactor.AbstractMultiworkerIOReactor$Worker.run(AbstractMultiworkerIOReactor.java:591)
    	at java.lang.Thread.run(java.base@15.0.2/Thread.java:832)
    Is it normal ? I have many beans defining ktor like this :
    @Named 
    class SomeBean {
      private val ktorClient = HttpClient {
        followRedirects = false
        expectSuccess = false
      }
    }
    It seems there is
    engine
    block can override
    threadsCount
    , but I never invoked it. Environments :
    <ktor.version>1.6.1</ktor.version>
    
          <dependency>
            <groupId>io.ktor</groupId>
            <artifactId>ktor-client-apache</artifactId>
            <version>${ktor.version}</version>
          </dependency>
    
    openjdk version "15.0.2" 2021-01-19
    OpenJDK Runtime Environment Zulu15.29+15-CA (build 15.0.2+7)
    OpenJDK 64-Bit Server VM Zulu15.29+15-CA (build 15.0.2+7, mixed mode)
    These threads are all green (RUNNING) when viewing in VisualVM , but they are not transmitting anything.
    j
    a
    13 replies · 3 participants
  • a

    Andre Servidoni

    07/27/2021, 2:55 PM
    hello all, i’m trying to download a 512 mb file with ktor, but after 250mb the app throws OOM. I’m justing showing what I receive
    val bytes = this
    val byteBufferSize = 1024 * 100
    val byteBuffer = ByteArray(byteBufferSize)
    
    do {
        val currentRead = bytes.readAvailable(byteBuffer, 0, byteBufferSize)
        if (currentRead > 0) {
            println("received: $currentRead")
        }
    
    } while (currentRead > 0)
    a
    17 replies · 2 participants
  • j

    John O'Reilly

    07/27/2021, 4:49 PM
    Is anyone by chance aware of any threading related changes that were made in
    MockEngine
    in 1.5.1.....we're updating a client here from a 1.4.x version and have isolated issue we're seeing to update from 1.5.0 to 1.5.1.....we have unit tests that are using
    runBlockingTest
    and getting
    IllegalStateException: This job has not completed yet
    after that update....digging deeper to try and narrow in on what's changed but just in case anyone encountered this before....
    j
    a
    +1
    19 replies · 4 participants
  • j

    Javier

    07/28/2021, 12:55 PM
    Is it possible to do a request inside load refresh token in the auth plugin without using another client?
    r
    13 replies · 2 participants
  • i

    Ido Flax

    07/28/2021, 7:15 PM
    Hello Ktor brains. We have a problem where when we have a ktor server endpoint returning a Unit response, it is not found by our ktor client (it gets a 404) where as if that same endpoint returns some non Unit response, it is found. Note we are using
    com.papsign.ktor.openapigen
    for swagger generation server endpoint with response (works):
    route("stuff"){
           jwtAuth {
                route("thing").post<Unit, Response, Request, UserPrincipal>(
                    info("Do a thing")
                ) { _, request ->
                    thingService.createThing(
                        principal().username,
                        request.thingName
                    )
                    status(HttpStatusCode.NoContent)
                    respond(Response())
                }
            }
    }
    Server endpoint without response (404ing):
    route("stuff"){
           jwtAuth {
                route("thing").post<Unit, Unit, Request, UserPrincipal>(
                    info("Do a thing")
                ) { _, request ->
                    thingService.createThing(
                        principal().username,
                        request.thingName
                    )
                    status(HttpStatusCode.NoContent)
                    respond(Unit)
                }
            }
    }
    Client:
    fun createHttpClient(
        authConfig: HttpAuthConfig? = null,
        connectionTimeout: Int = 5_000
    ) = HttpClient(Apache) {
        if (authConfig != null) {
            Auth {
                basic {
                    credentials {
                        BasicAuthCredentials(authConfig.username, authConfig.password)
                    }
                }
            }
        }
        engine {
            socketTimeout = connectionTimeout
            connectTimeout = connectionTimeout
            connectionRequestTimeout = connectionTimeout * 2
        }
        expectSuccess = false
    }
    
    ...
    
    fun HttpClient.withJsonSupport() = config {
        Json {
            serializer = KotlinxSerializer(kotlinx.serialization.json.Json {
                prettyPrint = true
                isLenient = true
                ignoreUnknownKeys = true
            })
            accept(ContentType.Any)
        }
    }
    
    ...
    
    private val jsonClient = createHttpClient().withJsonSupport()
    
    ...
    
    <http://jsonClient.post|jsonClient.post>("$url/stuff/thing") {
                headers {
                    append(
                        HttpHeaders.Authorization,
                        "Bearer $jwtToken"
                    )
                }
                contentType(ContentType.Application.Json)
                body = Request(thingName)
            }
    Is it possible that ktor client doesn’t respect Unit responses?
    a
    2 replies · 2 participants
  • g

    grigala

    07/28/2021, 9:52 PM
    install(CORS) {
            header(HttpHeaders.Range)
            header(HttpHeaders.XForwardedProto)
            header(HttpHeaders.AccessControlRequestHeaders)
            header("x-csrf-token")
            header("Authorization")
            anyHost()
            allowCredentials = true
            method(<http://HttpMethod.Post|HttpMethod.Post>)
            method(HttpMethod.Get)
            method(HttpMethod.Put)
            method(HttpMethod.Delete)
            method(HttpMethod.Head)
            method(HttpMethod.Options)
        }
    a
    1 reply · 2 participants
  • a

    Anders Oedlund

    07/29/2021, 10:55 PM
    I’ve noticed that sometimes (reasonably often) while using Ktor client with the Logging plugin installed on iOS in a KMM project some kind of deadlock occurs after
    log("BODY START")
    in the below function.
    private suspend fun logResponseBody(contentType: ContentType?, content: ByteReadChannel): Unit = with(logger) {
         log("BODY Content-Type: $contentType")
         log("BODY START")
         val message = content.tryReadText(contentType?.charset() ?: Charsets.UTF_8) ?: "[response body omitted]"
         log(message)
         log("BODY END")
    }
    Does anyone else have a similar experience, or any pointer how to avoid this (other than not installing the Logging plugin)?
    a
    2 replies · 2 participants
  • m

    Marc Knaup

    07/30/2021, 10:40 AM
    Hey there. How can I run logic before a websocket connection is established? I’d like to validate URL parameters before the websocket session starts so that I can return 404 for invalid parameters for example. The only way I can think of is using
    install()
    to intercept the call.
    a
    6 replies · 2 participants
  • d

    Dominick

    08/01/2021, 1:57 AM
    Is there any ratelimiting feature that does all of this: • Custom ratelimits based on endpoint • Custom key to determine who the sender is (an Ip address) • Standard HTTP header responses like when to resend, etc
    h
    1 reply · 2 participants
  • e

    Ehtesham Shahzad

    08/01/2021, 11:21 AM
    Hello everyone. I am choosing between Spring Boot and Ktor for a project. With time, this project will scale to a large scale project. My question is: is Ktor ready and suitable for large scale projects (with evolving requirements)? Or should I go with Spring Boot?
    :ktor: 1
    ☝️ 1
    c
    m
    2 replies · 3 participants
  • j

    Jgafner

    08/01/2021, 3:45 PM
    Hi Small question about development mode : Is it possible to let ktor decide which modules to load based on development mode ? If not is it possible with a custom property in the conf like in the example: https://ktor.io/docs/configurations.html#custom-property ? Thanks
    a
    5 replies · 2 participants
Powered by Linen
Title
j

Jgafner

08/01/2021, 3:45 PM
Hi Small question about development mode : Is it possible to let ktor decide which modules to load based on development mode ? If not is it possible with a custom property in the conf like in the example: https://ktor.io/docs/configurations.html#custom-property ? Thanks
a

Aleksei Tirman [JB]

08/01/2021, 3:56 PM
Is it possible to let ktor decide which modules to load based on development mode ?
No. The best thing you can do is to wrap a module's code with a check for the
developmentMode
or custom property condition. Here is an example:
embeddedServer(Netty, applicationEngineEnvironment {
    connector {
        port = 7070
    }

    module {
        if (developmentMode) {
            routing {
                get("/") {
                    call.respondText { "You will see it in the development mode" }
                }
            }
        }
    }
}).start()
j

Jgafner

08/01/2021, 4:01 PM
Thanks @Aleksei Tirman [JB] - do you know it possible to pass which hocon file to use in the command line ? or maybe some feature like spring config profiles? so we can set some of the configuration to be enable in certain cases ? Thanks again
a

Aleksei Tirman [JB]

08/01/2021, 4:03 PM
You can use
-config
CLI argument to specify the path to a HOCON file.
j

Jgafner

08/01/2021, 4:04 PM
thanks
a

Aleksei Tirman [JB]

08/01/2021, 4:04 PM
or maybe some feature like spring config profiles?
I don't know about such a feature.
View count: 1