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

    Alex Cruise

    08/12/2022, 5:04 PM
    Is there a way to add a suffix/tag to logs based on which module/plugin/etc. is doing the logging? Right now it’s always
    Application
    a
    f
    • 3
    • 7
  • s

    spierce7

    08/12/2022, 8:07 PM
    If I wanted to reject a request because a file is too large, without downloading the entire file on my server, what’s the best way to do that? Will something like the code in the thread handle that?
    a
    • 2
    • 2
  • a

    Alper Tekin

    08/13/2022, 11:40 AM
    Hi Ktorers 👋 I have ktor microservices and firebase authentication. There is no problem while verifying tokens when a request received to an endpoint. But also I have clients in microservices that talks to each other, I couldn’t find a way to set token to the clients 😅 I also use consul to discover services. I may elaborate in case you need more info 🙂 My approach looks like the project below: https://github.com/marcguilera/ktor-bank/blob/master/balance/balance-client/src/ma[…]marcguilera/bank/balance/client/default/DefaultBalanceClient.kt
    a
    • 2
    • 2
  • m

    martmists

    08/13/2022, 1:54 PM
    Having an issue in ktor server (jvm, 2.1.0)
    kotlin.reflect.full.IllegalCallableAccessException: java.lang.IllegalAccessException: class kotlin.reflect.jvm.internal.calls.CallerImpl$FieldGetter cannot access a member of class team.luminescent.site.auth.DiscordAuthPrincipal with modifiers "private final"
    The DiscordAuthPrincipal is just an oauth principal:
    data class DiscordAuthPrincipal(val accessToken: String, val refreshToken: String) : Principal {
        fun isValid(): Boolean {
            // Fetch API to do additional checks
        }
    }
    Code:
    exception<Exception> { call, err ->
                call.respondTemplate(HttpStatusCode.InternalServerError, "pages/error/500", mapOf(
                    "error" to err.stackTraceToString()
                ))
            }
  • m

    martmists

    08/13/2022, 5:27 PM
    Oh I see, it's because it holds a lazily computed value that I don't want to recalculate every isValid call, but that breaks the builtin serialization.
  • h

    Hamza GATTAL

    08/13/2022, 6:53 PM
    Hi everyone Could you please give me an example how to download a file using ktor client.
    d
    b
    n
    • 4
    • 4
  • r

    Rajput Art Studio

    08/14/2022, 5:29 AM
    Hi Team Facing one issue in Android ktor client. When sending multipart data with image then it throws error Multipart class not a serialised class. How to implement a ktor inbuild class with serialised annotation. Thanks in advance
    p
    a
    • 3
    • 3
  • t

    Tóth István Zoltán

    08/16/2022, 4:06 AM
    Hi! Is it possible to add path based authorisation to files served with
    static { ... }
    ? What I would like to do: • user A can access files from
    ./a
    folder • user B can access files from
    ./a
    and
    ./b
    folders Authentication is done in a very different part of the application. I wouldn't touch that if there is a way. Actually, I shouldn't touch that as authentication and authorisation are two different topics. As I see, my only option right now is to write (i.e. cut&paste from Ktor) my own handling of static resources and add the authorisation. Are there any better options? Thanks in advance.
    a
    a
    • 3
    • 4
  • l

    Leon Kiefer

    08/16/2022, 4:50 PM
    Hi, do I have to close a ktor client A if I create it with
    HttpClient.config
    from another client B, or do I only need to close the client B?
    a
    • 2
    • 1
  • w

    William Reed

    08/16/2022, 6:27 PM
    any recommended resources for seeing companies that currently use ktor in production? i’m trying to write up a document advocating for ktor at work
    s
    • 2
    • 2
  • r

    Ryan Brink

    08/17/2022, 1:24 AM
    hey everyone… I’m still keeping my fingers crossed for an official jetbrains solution for generating api documentation for ktor, but in the meantime, I have updated Kompendium to support Ktor 2 https://github.com/bkbnio/kompendium
    e
    • 2
    • 1
  • a

    Ananiya

    08/17/2022, 12:37 PM
    any way to send
    BufferedImage
    over websocket efficiently 1 tried to deserilize the constructor using GSON because it has nested object resulting the https://stackoverflow.com/questions/43301580/gson-cant-serialize-bufferedimages 2 tried kotlinx serilization , doesn't work since
    BufferedImage
    has no
    @Serilizable
    annotation 3 tried converting buffered image -> float array -> to string(using joinToString) kind of worked but its super slow and unresponsive 4 tried converting buffered image -> bytearray using
    ByteArrayOutputStream
    and
    ImageIO.write()
    has made significant improvement but still unusable I don't think the
    IO
    method would be any efficient but if there's any way to send the whole
    BufferedImage
    object or deserilizing it without using IO would be take less time
    a
    • 2
    • 4
  • n

    Niko

    08/17/2022, 4:33 PM
    I'm building a service that offers a documents-system that acts in similar way as the Static contents plugin's
    static {}
    block that offers serving static files, but with my system markdown pages are lazily converted to HTML, cached and served. I'm thinking how I could decouple deploying the service and the documents to allow more dynamic deploy and update of the actual documents. Currently the block resolves the files from classpath, but I was thinking additionally I could write logic to check a configurable path, to allow running the service inside container with mounted docs path. Other thing I thought was, if I could implement a way to deploy additional jar containing only the documents to same classpath the service runs in. Any inside or pointers, in achieving any of the two, or another way?
    a
    • 2
    • 2
  • n

    napperley

    08/18/2022, 3:03 AM
    With Ktor Server how is a binary file read from the request body?
    t
    a
    • 3
    • 5
  • j

    Jerry Yion

    08/18/2022, 6:40 AM
    Is it good to set a base url like Retrofit in using ktor?
    a
    • 2
    • 2
  • d

    ddimitrov

    08/18/2022, 3:20 PM
    Hi All, I am new to Ktor so I may be missing something obvious. I am trying to use the testing hostfor my server following the instructions on the Ktor Server Testing> page from the manual. In particular, the last example shows this:
    fun testPostCustomer() = testApplication {
        val client = createClient {
            install(ContentNegotiation) {
                json()
            }
        }
        val response = <http://client.post|client.post>("/customer") {
            contentType(ContentType.Application.Json)
            setBody(Customer(3, "Jet", "Brains"))
        }
        assertEquals("Customer stored correctly", response.bodyAsText())
        assertEquals(HttpStatusCode.Created, response.status)
    }
    I find that to be broken, as the closure argument of the test application configures the application builder, and executing the stimuli and the assertions mean that you are running these from your app config code before the app is started. I am not even sure how it ever works, even if sometimes it does. In my case, my app is starting an event pump for external Java API (think TIBCO RV) from the ApplicationStarted event, and this callback is invoked at the end of the test, after all assertions have failed (I found that only after commenting out a lot of code). Raised: https://youtrack.jetbrains.com/issue/KTOR-4773
  • d

    ddimitrov

    08/18/2022, 3:45 PM
    Unrelated question, I can see that the KTor test fixtures use JUnit4 APIs. Is it possible to somehow use with JUnit5 Jupiter?
    a
    • 2
    • 1
  • b

    bbaldino

    08/19/2022, 5:10 PM
    I'm trying to better understanding the threading ktor uses in the websocket handler (mainly: how many threads are backing it and how are they leveraged, i.e. can another websocket be opened while one is currently being processed?), but haven't found much in the way of documentation on it, does anyone know of anything?
  • j

    Joe Altidore

    08/19/2022, 10:19 PM
    Hello guys! Please, I need help with writing a migration script for mySql database in Ktor server project. Thanks.
    h
    • 2
    • 3
  • z

    zt

    08/22/2022, 12:32 AM
    I'm using ktor on android and im having a crash that only occurs in the system emulator with the CIO engine which doesn't occur when using the Android engine. It only happens with a request to
    <https://www.youtube.com>
    , using some other url like
    <https://www.github.com>
    works fine with both CIO and Android.
    HttpClient(CIO).get("<https://youtube.com>")
    java.net.SocketException: Network is unreachable
    	at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
    	at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:762)
    	at io.ktor.network.sockets.SocketImpl.connect$ktor_network(SocketImpl.kt:50)
    	at io.ktor.network.sockets.SocketImpl$connect$1.invokeSuspend(Unknown Source:15)
    	at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    	at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
    	at kotlinx.coroutines.internal.LimitedDispatcher.run(LimitedDispatcher.kt:42)
    	at kotlinx.coroutines.scheduling.TaskImpl.run(Tasks.kt:95)
    	at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:570)
    	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:
    	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:67
    	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:664)
  • f

    fair_enough

    08/22/2022, 11:19 AM
    Hi al, I am using Ktor client to Kror server. I am using cokies. And Without CORS, it works fine
    install(Sessions) {
        cookie<RegularUserSession>("regular_user_session", SessionStorageMemory())
        cookie<GoogleUserSession>("google_user_session", SessionStorageMemory())
    }
    install(CORS) {
        allowHeader("regular_user_session")
        exposeHeader("regular_user_session")
        allowHeader("google_user_session")
        exposeHeader("google_user_session")
        allowMethod(HttpMethod.Options)
        allowMethod(HttpMethod.Put)
        allowMethod(HttpMethod.Delete)
        allowMethod(HttpMethod.Patch)
        allowHeader(HttpHeaders.Authorization)
        allowHeader(HttpHeaders.AccessControlAllowOrigin)
        allowNonSimpleContentTypes = true
        allowSameOrigin = true
        anyHost()
    }
    tried allowHeader only or exposeHeader only or both
    HttpClient(engineFactory) {
        install(HttpCookies)
    }
    On same host client: 1. Connection: keep-alive 2. Content-Encoding: deflate 3. Content-Type: application/json 4. Set-Cookie: regular_user_session=75f7618f14d56eaa81f04b0564146e4d; Max-Age=604800; Expires=Mon, 29 Aug 2022 11🔟24 GMT; Path=/; HttpOnly; $x-enc=URI_ENCODING 5. transfer-encoding: chunked On COSRS client: 1. Access-Control-Allow-Origin: * 2. Access-Control-Expose-Headers: google_user_session, regular_user_session 3. Connection: keep-alive 4. Content-Encoding: deflate 5. Content-Type: application/json 6. Set-Cookie: regular_user_session=a848eb176774abd4ded030892bc5615f; Max-Age=604800; Expires=Mon, 29 Aug 2022 11:09:31 GMT; Path=/; HttpOnly; $x-enc=URI_ENCODING 7. transfer-encoding: chunked But it still doesn't works on CORS client. I dont know why
    a
    a
    • 3
    • 32
  • a

    August Lilleaas

    08/22/2022, 11:21 AM
    hi folks! I asked a more generic version of this in #server, but thought I’d ask here as well, seeing as this is as far as I can tell a bug/issue in ktor - as long as I’m not just missing some detail here 🙂 ktor-servlet defines the extension function
    ApplicationRequest.javaSecurityPrincipal
    , in
    io/ktor/server/servlet/JAASBridge.kt
    which checks if the request
    is ServletApplicationRequest
    . As far as I can tell, this never works, since the request is always a
    RoutingApplicationRequest
    that delegates to the original request in
    io/ktor/server/routing/RoutingApplicationCall.kt
    - i.e. the
    is
    check doesn’t find the
    ServletApplicationRequest
    instance, just the
    RoutingApplicationRequest
    , as
    is
    does not check for delegates (?). Is this a bug? Or is there some other way to access the principal on the servlet request from Ktor?
    a
    • 2
    • 6
  • a

    amadeu01

    08/23/2022, 8:55 AM
    hi all, have you done anything like using annotations for experimental routes ? And, only make that routes available for a specific environment ? I’m thinking of using https://kotlinlang.org/docs/opt-in-requirements.html to limited the usage of some routes, have you done this?
    a
    • 2
    • 1
  • f

    fair_enough

    08/24/2022, 4:18 PM
    Maybe stupid question. I implemented br compression. Compression works. BUT when I am on localhost, browser set
    Accept-Encoding: gzip, deflate, br
    and I am receiving br. But, when I am accessing same server from LAN ip or domain, browser set only
    Accept-Encoding: gzip, deflate
    , so I get only gzip. Any ideas?
    d
    • 2
    • 5
  • k

    KamilH

    08/25/2022, 6:17 AM
    Is it possible to use new, okio based serialization API in conjunction with ktor?
    a
    • 2
    • 4
  • k

    kevin.cianfarini

    08/25/2022, 1:01 PM
    I'm getting a mysterious exception with Ktor client
    2.0.3
    with cURL on K/N with the new memory manager on
    linuxX64
    . It always happens on the second network request for a given "service". Here's an abbreviated stracktrace.
    Uncaught Kotlin exception: kotlinx.coroutines.JobCancellationException: Parent job is Completed; job=JobImpl{Completed}@162aaa80
        at 0   permit-data.kexe                    0x42fd70           kfun:kotlin.Exception#<init>(kotlin.String?;kotlin.Throwable?){} + 128 
        at 1   permit-data.kexe                    0x42ff20           kfun:kotlin.RuntimeException#<init>(kotlin.String?;kotlin.Throwable?){} + 128 
        at 2   permit-data.kexe                    0x4304a0           kfun:kotlin.IllegalStateException#<init>(kotlin.String?;kotlin.Throwable?){} + 128 
        at 3   permit-data.kexe                    0x43bf30           kfun:kotlin.coroutines.cancellation.CancellationException#<init>(kotlin.String?;kotlin.Throwable?){} + 128
    Full stacktrace is in thread. I'm going to keep digging in, Is this perhaps a problems with ktor client?
    a
    • 2
    • 11
  • t

    Trey

    08/25/2022, 4:24 PM
    Is there a way to easily debug the above issue? To see when the parent job is completed with maybe a stack trace? This issue seems to pop up a lot with people using ktor.
  • b

    Brent Beardsley

    08/25/2022, 4:29 PM
    Is there a way to use
    OkHttp
    ktor client in a
    testApplication
    block? We're seeing channel closed issues with the default client and was trying to work around it.
    a
    • 2
    • 3
  • r

    Raymond Zeng

    08/26/2022, 1:00 AM
    Hey folks, looking for experiences on DI with Ktor. What's the "typical setup" like - just creating modules (either with Koin/Kodein or manually) and passing them into the extension functions? Has anyone experimented with a library like Kotlin-Inject with Ktor? Thanks in advance!
    a
    • 2
    • 2
  • m

    Ming Chun Or

    08/26/2022, 3:54 AM
    Hi. Is there a way for Ktor client to interrupt while downloading the response if it get too large? I have try to take a look at custom plugin and
    onDwonload
    hook but it seems didn’t help. The
    response.bodyAsChannel()
    seems to be returning the whole response (buffered into memory?) before I can check and consume it. I want to cut the underlying HTTP call early if the response size is too large.
    a
    • 2
    • 3
Powered by Linen
Title
m

Ming Chun Or

08/26/2022, 3:54 AM
Hi. Is there a way for Ktor client to interrupt while downloading the response if it get too large? I have try to take a look at custom plugin and
onDwonload
hook but it seems didn’t help. The
response.bodyAsChannel()
seems to be returning the whole response (buffered into memory?) before I can check and consume it. I want to cut the underlying HTTP call early if the response size is too large.
The
BodyProgress
plugin behind
onDownload
only allow me to put listener on the download content size but did not allow me to cancel the
Job
a

Aleksei Tirman [JB]

08/26/2022, 6:23 AM
You can create an instance of
HttpRequestBuilder
manually to be able to refer to its
executionContext
property which you can use to cancel a job. Here is an example:
suspend fun main(): Unit = runBlocking {
    val client = HttpClient(Apache)

    val builder = HttpRequestBuilder().apply {
        url("<http://127.0.0.1:3333>")
        onDownload { bytesSentTotal, contentLength ->
            // executionContext.cancel() will work too
            println("Received $bytesSentTotal bytes from $contentLength")
        }
    }

    launch {
        delay(200)
        builder.executionContext.cancel()
    }

    client.get(builder)
}
m

Ming Chun Or

08/26/2022, 7:04 AM
onDownload { bytesSentTotal, contentLength ->
  executionContext.cancel()
}
It work perfectly! Thx ❤️
View count: 16