https://kotlinlang.org logo
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

    Satyam Agarwal

    11/13/2022, 1:10 PM
    Hey ! What order plugins get called if there are multiple plugins performing operations on one phase ? For example on call setup phase (
    on(CallSetup)
    ) I have three different plugins registered. What is the execution strategy ?
    a
    • 2
    • 3
  • a

    Antonio Acuña Prieto

    11/15/2022, 8:27 PM
    Anyone deploying Ktor service using Railway?
  • s

    Stylianos Gakis

    11/15/2022, 10:10 PM
    I wonder, is there any tool which takes an OpenAPI yml file, and generates a ktor client with all the existing endpoints?
    b
    f
    +2
    • 5
    • 7
  • l

    Luiz Aguiar

    11/16/2022, 10:55 PM
    very basic… but why this test code is not compiling on the
    install
    statement?
    @Test
        fun testOptimizeRouter() = testApplication {
            val client = createClient {
                install(ContentNegotiation) {
                    json()
                }
            }
            // omitted
         }
    Ktor 2.1.3 Kotlin 1.7.21 IDEA CE 2022.3 Beta (EAP)
    h
    r
    • 3
    • 5
  • b

    Bruno Ranschaert

    11/18/2022, 12:14 PM
    Hi, I wrote a HttpClient plugin to change the auth header for some requests; so far so good. I do not want the user to get the session cookie, so I want to strip the "set-cookie" header from the response. The headers in the response object are read-only. Is there a location (intercept) somewhere where I could change the response headers?
    scope.requestPipeline.intercept(HttpRequestPipeline.State) {
       // inject auth header here - works fine
       val clientCall = proceedWith(subject)
       // Remove session cookie here - don't know how to do this
    }
    r
    • 2
    • 2
  • p

    Piotr Krzemiński

    11/18/2022, 12:47 PM
    does someone have a working example of hosting a JS frontend from within ktor server? I’m aware of singlePageApplication routing and I achieved something like this like a year or two with a bunch of custom logic, but now I want to use the idiomatic way I’m stuck in a place where I have two projects: the one in Kotlin/JS (React) that produces a working bundle in
    build/distributions
    , and another module with a working ktor server. What’s the idiomatic way to declare a dependency on the web UI project form the ktor project, copy over the bundle to the ktor module and serve it from ktor? My ultimate goal is being able to create a Docker image with the server hosting the web UI, so I presume the bundle should land somewhere in JVM
    resources
    b
    c
    • 3
    • 19
  • i

    IsaacMart

    11/21/2022, 8:57 AM
    Is there a way to schedule a task in ktor? I want to sechedule a task for 20 minutes if they are over, that task should be marked expired. Am having idea of using delay but not sure if its tye best approach so far.Any one please?
    r
    o
    +2
    • 5
    • 20
  • f

    FunkyMuse

    11/21/2022, 10:23 PM
    hey guys, does anyone know any alternate way of registering everything in the application receiver object, this seems to grow a lot when you add stuff and can become quite messy
    a
    • 2
    • 2
  • r

    Richard Schielek

    11/22/2022, 1:06 PM
    Is it possible to send a chunked response with ktor-server? Here is what it looks like in vertx:
    val response = request.response()
    val channel = response.toSendChannel(vertx)
    
    response.headers().set("Transfer-Encoding", "chunked")
    
    for (i in 1..10) {
      delay(200)
      channel.send(Buffer.buffer("""{"id": $i}"""))
      channel.send(Buffer.buffer("\n"))
    }
    
    response.end().await()
    a
    • 2
    • 2
  • a

    Alberto Quario

    11/22/2022, 2:29 PM
    Hello, we have a sequence of tests like:
    should("respond OK") {
        testApplication {
            application {
                mockService("11111111111")
                configureServing()
                configureRouting()
            }
            client.get("/v1/foo/XXX00000000123").apply {
                assertEquals(HttpStatusCode.OK, status)
            }
        }
    }
    should("respond to Unauthorized") {
        testApplication {
            application {
                mockService("12345678")
                configureServing()
                configureRouting()
            }
            client.get("/v1/foo/XXX00000000123").apply {
                assertEquals(HttpStatusCode.Unauthorized, status)
            }
        }
    }
    and the mockService mock a static builder using mockk
    private fun mockService(id: String?) {
        mockkObject(ReferenceClientBuilder)
        val fakeService = mockk<ReferenceClient>()
        coEvery { fakeService.customerId(any()) } returns id
        ...
        coEvery { ReferenceClientBuilder.getClient(any()) } returns fakeService
    }
    Up to ktor 2.1.2 everything was ok, but now with 2.1.3 the second test fails cause the static mockk is just set on the first test and not updated on following ones. Any hints? Thanks!
    a
    • 2
    • 2
  • d

    dodalovic

    11/23/2022, 8:54 PM
    Hi, I'm trying to use https://ktor.io/docs/response-validation.html#2xx and in there to use request attributes so, something like:
    httpClient.get("/whatever") {
       attributes.put("operation", "whatever")
    }
    and then in my validator:
    val client = HttpClient(CIO) {
        install(ContentNegotiation) { json() }
        HttpResponseValidator {
            validateResponse { response ->
              if response.request.attributes["operation"] == "whatever"
              //whatever
            }
        }
    }
    is this possible at all
    a
    • 2
    • 2
  • m

    MarkRS

    11/24/2022, 11:00 AM
    Do I have to do something different in KTor 2.x to receive nested JSon classes? I haven't been able to find anything obvious in the KTor serialisation docs. I have a receivable class that arrives perfectly well in one call as an array of this class, but when (in another call) it's a property of a larger class no data (for it) is de-serialised. Although I'm certain the data is sent from the server, it doesn't show up in the log of the received data, which also seems strange. I know this sounds like a foolish question but it used to work, although I'm not sure if this failure is due to the KTor 2.x update or something else.
    a
    • 2
    • 24
  • h

    hhariri

    11/25/2022, 11:11 AM
    📣 Announcement: Marketplace Feedback We are starting work on the marketplace, which will allow Ktor users to discover and use 3rd party Ktor plugins. Whether you're a consumer of these plugins or publish Ktor plugins, we would really love to have a chat with you and make sure that the challenges you are facing would be accounted for. Please ping me or reply in this message if you'd like to discuss and work a bit closer on this matter with us.
  • j

    James Chen

    11/25/2022, 6:39 PM
    Hi Team! I'm still new to ktor/kotlin, and have been playing around with the framework for websocket development. My current project is a websocket proxy (we accept a ws connection, and create a connection to another backend ws server, and route messages between them). The code works fine, but I'm having issues with setting up tests for this, specifically with trying to mock out the backend ws server with
    externalServices
    . This is the mock I have right now in my `testApplication`:
    externalServices {
        hosts("<ws://test.com>") {
            install(io.ktor.server.websocket.WebSockets) {}
            routing {
                webSocket("/") {
                    this.send("hello")
                }
            }
        }
    }
    My test will hang when it tries to connect to
    <ws://test.com>
    and eventually return a
    io.ktor.client.network.sockets.ConnectTimeoutException: Connect timeout has expired [url=<ws://test.com>, connect_timeout=unknown ms]
    error. Can
    externalServices
    mock out ws servers? If not, are there any suggestions on how to mock a ws server for testing? Thank you!
    a
    • 2
    • 2
  • d

    dino9

    11/25/2022, 7:21 PM
    Hello Team, How do we suppose to parse this json using ktor client?
    {
      "base": "xyz",
      "rates": {
        "AED": 3.67295,
        "AFN": 87.499995
      }
    }
    @Serializable
    class Obj(val base: String, val rates : Map<String?,Double>?)
    I use kotlin serialization but observed following error
    io.ktor.client.call.NoTransformationFoundException: No transformation found: class io.ktor.utils.io.ByteBufferChannel (Kotlin reflection is not available) -> class dev.packge (Kotlin reflection is not available)
    e
    • 2
    • 3
  • j

    James Chen

    11/26/2022, 6:18 AM
    I'm seeing odd behavior If i create an
    HttpClient
    from an
    ApplicationTestBuilder()
    in a test, or create an
    HttpClient
    mockk, and inject that into my code path that uses a normal
    HttpClient
    (e.g.
    HttpClient(CIO)
    ) during a
    testApplication
    run. Odd side effects include authentication principals becoming null, and testcontainers not being recognized. For context I'm trying to do this to mock out some behaviors for testing. Does anyone know why this is?
    a
    • 2
    • 1
  • d

    dave08

    11/27/2022, 12:51 PM
    I'm trying to implement a Moshi ContentConverter, but when I run the tests in
    JsonContentNegotiationTest
    for it, it fails testBadlyFormattedJson, that it expects a BAD REQUEST... what am I doing wrong? (code in the thread)
    a
    • 2
    • 4
  • r

    Richard Schielek

    11/27/2022, 5:29 PM
    When defining a route that runs into an exception ktor will return an internal server error (500) by default.
    fun Application.configureRouting() {
        routing {
            get("/") {
                error("Something went wrong")
            }
        }
    }
    But when using this in a test, the test application will not return a 500 but throw the exception instead
    class ApplicationTest {
        @Test
        fun testRoot() = testApplication {
            application {
                configureRouting()
            }
            
            val response = client.get("/") // java.lang.IllegalStateException: Something went wrong
            assertEquals(HttpStatusCode.InternalServerError, response.status)
        }
    }
    How do I test this behavior when I rely on the default implementation of ktor?
    r
    • 2
    • 4
  • f

    FunkyMuse

    11/27/2022, 11:21 PM
    Hey everyone, is there any more up to date redis sample other than https://github.com/ktorio/ktor-clients/tree/main/ktor-client-redis/src/io/ktor/experimental/client/redis
  • d

    dave08

    11/28/2022, 2:09 PM
    What is this:
    'fun <P : Pipeline<*, ApplicationCall>, B : Any, F : Any> install(plugin: Plugin<Application, AuthenticationConfig, Authentication>, configure: AuthenticationConfig.() -> Unit = ...): Unit' can't be called in this context by implicit receiver. Use the explicit one if necessary
    ?
  • d

    dave08

    11/28/2022, 2:11 PM
    I had to do
    this@testApplication.install(...)
    🙈...
  • d

    dave08

    11/28/2022, 2:20 PM
    Now I'm getting
    The test application has already been built. Make sure you configure the application before accessing the client for the first time.
    🤕... I wish Ktor would just let me create my own
    testApplication
    without trying to magically find an existing one...
    e
    a
    r
    • 4
    • 27
  • s

    spierce7

    11/28/2022, 3:42 PM
    I see several tickets that were closed earlier for setting a base url / path. How would we properly set a base url and path for requests in ktor?
    a
    • 2
    • 1
  • t

    Trey

    11/28/2022, 7:54 PM
    Is there a way to configure the HttpBuilder so that it won't encode the path? Android doesn't encode, but iOS does. "/v3/subscribers%3Bview=subuser_overview" vs"/v3/subscribers;view=subuser_overview" The difference causes my app to get a 404 vs the proper response.
    Untitled.txt
    a
    • 2
    • 2
  • c

    Chris Ryder

    11/29/2022, 5:27 PM
    Hi, can anyone point me to an example of a Ktor app authenticating with Azure AD?
    k
    • 2
    • 1
  • c

    Colin L

    11/30/2022, 4:52 AM
    :android-wave:Hi, I'm evaluating Ktor and was wondering what benchmarking tools folks use. I've used hey for Golang and Scala applications, and I'm seeing mixed behaviour when I run Ktor with both Netty and CIO natively on an M1 mac, as well as within Docker of the same architecture (ARM). I seem to max out at 125 connections with Netty both on the host and within a container. For CIO, I max out at 500 connections on the host, but 125 in a container. Wondering what I might need to configure/tune.
  • j

    João Gabriel Zó

    11/30/2022, 12:16 PM
    I’m receiving this when trying to run my application
    Correct the classpath of your application so that it contains compatible versions of the classes io.ktor.client.utils.CoroutineDispatcherUtilsKt and kotlinx.coroutines.CoroutineDispatcher
    which versions would be compatible in this case?
    c
    a
    • 3
    • 3
  • a

    Alex Styl

    12/01/2022, 7:12 AM
    Is there a way to listen to the progress of a file being uploaded to a ktor server from the server side? I have a ktor server running in an Android app and I would like to display a progress bar while the ktor server is receiving the file. my code looks like this:
    // 1
    call.receiveMultipart().forEachPart { part ->
        // 2
        when (part) {
            is PartData.FileItem -> {
                val input = part.provider()
                // Read from input by chunks
            }
            else -> {}
        }
    }
    I would like to listen to the progress between (1) and (2). Right now (1) is called, then the file is fully uploaded to the server, and then (2) is called.
    f
    e
    +2
    • 5
    • 13
  • c

    Cherrio LLC

    12/03/2022, 12:16 PM
    While testing redirects on Ktor client, i got
    SendCountException
    . Code in 🧵
    a
    • 2
    • 6
  • z

    zt

    12/06/2022, 1:52 AM
    How do I read a text/event-stream content type? In my API its being used as a sort of progress indicator. So each newline contains some data. I need to get the last line in the stream
    c
    • 2
    • 2
Powered by Linen
Title
z

zt

12/06/2022, 1:52 AM
How do I read a text/event-stream content type? In my API its being used as a sort of progress indicator. So each newline contains some data. I need to get the last line in the stream
c

Chris Fillmore

12/06/2022, 2:09 AM
I don’t think Ktor supports this out of the box. However, you can do this with OkHttp directly https://square.github.io/okhttp/3.x/okhttp-sse/index-all.html
z

zt

12/06/2022, 3:46 AM
Just found this, https://youtrack.jetbrains.com/issue/KTOR-505
View count: 20