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

    Shalaga44

    09/05/2020, 1:42 AM
    Hi, I'm newbie trying to use KMP to build a full stack web app using Ktor in jvmMain as back-end and Kotlin-React in jsMain as front-end, How can I add all jsMain source set to ktor watch path to enable automatic reload .
    fun main() {
        embeddedServer(
            Netty, watchPaths = listOf("jvmMain"), port = 8080,
            module = Application::myModule
        ).start(wait = true)
    }
    fun Application.myModule() {
        routing {
            get("/") {
                call.respondHtml(HttpStatusCode.OK, HTML::index)
            }
            static("/static") {
                resources()
            }
        }
    }
    n
    • 2
    • 1
  • c

    Chris Fillmore

    09/06/2020, 3:35 AM
    Hello, I have filed a bug about HttpStatement#toString causing InvalidArgumentException: https://youtrack.jetbrains.com/issue/KTOR-1005
    e
    • 2
    • 1
  • f

    fkrauthan

    09/06/2020, 10:06 PM
    anyone experience with a good coroutine supported rabbitmq client to listen for events? (not sure if there is a better channel for this question but I thought since many of you develop microservices where queue processing might be involved I try it here first)
    n
    • 2
    • 5
  • f

    fkrauthan

    09/07/2020, 2:36 AM
    Now I have a ktor client specific question. If I develop a custom feature (that does for example some custom authentication logic/signing of payloads) but needs to use user specific details (my app is multi user capable). How would I go about that? Would I need to create a new client instance for each user and then pass the specific client credentials as part of the Feature setup? Or is there are a better way. For Feign client I for example used ThreadLocal to pass in this information. So before calling the HttpClient I was setting the ThreadLocal with the required info. is there something similar for ktor client and ktor client Features?
    j
    f
    • 3
    • 4
  • a

    andylamax

    09/07/2020, 2:18 PM
    How do I serve folders (not files) using ktor? I wan't to expose a certain directory that can be traversed in the browser via ktor. Solutions?
    d
    j
    • 3
    • 6
  • h

    Hexa

    09/07/2020, 6:28 PM
    Does Ktor support swagger? I don't think it does as I have not seen any docs on it, so how do you document your Ktor endpoints?
    s
    j
    • 3
    • 2
  • f

    fkrauthan

    09/08/2020, 4:42 AM
    For my question above about passing in dynamic values to a Feature. I just found the concept of attributes. Would the idea be to inject the dynamic auth based on user session into an attribute and then read the attribute in my custom auth feature to set the correct header information? or is the attribute system intended for something else?
    e
    • 2
    • 1
  • g

    gotoOla

    09/08/2020, 1:17 PM
    Hi everybody! Going for a question here as I'm out of luck in my debugging of this weird behavior. Just putting it out here to see if anybody else has experienced or seen something similar or has some good advice on where to go next We are getting requests in to a ktor server, that in turn then calls 3 other services using three different instantiations of ktor client. We regularly see that we get IOException: Connection reset by peer in the calls we are making. I started to add some traceId parameters to the calls to be able to see what happened in the other services (remember, these are three unrelated services but each of them gave this error every once in a while) but it seems the calls never found their way to these services, making me think that there is maybe a bug in the internal ktor client? We tried it with both Apache and CIO as an engine and got the same result. Now I changed to OkHttpClient and I don't see this anymore
    stack_trace	   	java.io.IOException: Connection reset by peer
    	at (Coroutine boundary.()
    	at io.ktor.client.engine.apache.ApacheEngine.execute(ApacheEngine.kt:23)
    	at io.ktor.client.engine.HttpClientEngine$install$1.invokeSuspend(HttpClientEngine.kt:49)
    	at io.ktor.client.features.HttpSend$DefaultSender.execute(HttpSend.kt:90)
    	at io.ktor.client.features.HttpSend$Feature$install$1.invokeSuspend(HttpSend.kt:62)
    	at io.ktor.client.HttpClient.execute(HttpClient.kt:141)
    	at io.ktor.client.call.HttpClientCallKt.call(HttpClientCall.kt:140)
    	at mycompany.clients.SearchClient.getSearch(SearchClient.kt:76)
    	at mycompany.services.SearchService$getPrerequisits$2.invokeSuspend(SearchService.kt:28)
    	at mycompany.endpoints.SearchEndpoints$createRoutes$1$1$2.invokeSuspend(ExportEndpoints.kt:61)
    	at mycompany.core.ktor.Router_extensionsKt$postAndReportMetrics$2.invokeSuspend(router_extensions.kt:57)
    	at io.ktor.routing.Routing.executeResult(Routing.kt:147)
    	at io.ktor.routing.Routing$Feature$install$1.invokeSuspend(Routing.kt:99)
    	at io.ktor.server.engine.DefaultEnginePipelineKt$defaultEnginePipeline$2.invokeSuspend(DefaultEnginePipeline.kt:118)
    	at io.ktor.server.netty.NettyApplicationCallHandler$handleRequest$1.invokeSuspend(NettyApplicationCallHandler.kt:36)
    Caused by: java.io.IOException: Connection reset by peer
    	at sun.nio.ch.FileDispatcherImpl.read0(Native Method)
    	at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:39)
    	at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223)
    	at sun.nio.ch.IOUtil.read(IOUtil.java:197)
    	at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:377)
    	at org.apache.http.nio.reactor.ssl.SSLIOSession.receiveEncryptedData(SSLIOSession.java:444)
    	at org.apache.http.nio.reactor.ssl.SSLIOSession.isAppInputReady(SSLIOSession.java:499)
    	at org.apache.http.impl.nio.reactor.AbstractIODispatch.inputReady(AbstractIODispatch.java:120)
    	at org.apache.http.impl.nio.reactor.BaseIOReactor.readable(BaseIOReactor.java:162)
    	at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvent(AbstractIOReactor.java:337)
    	at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvents(AbstractIOReactor.java:315)
    	at org.apache.http.impl.nio.reactor.AbstractIOReactor.execute(AbstractIOReactor.java:276)
    	at org.apache.http.impl.nio.reactor.BaseIOReactor.execute(BaseIOReactor.java:104)
    	at org.apache.http.impl.nio.reactor.AbstractMultiworkerIOReactor$Worker.run(AbstractMultiworkerIOReactor.java:588)
    	at java.lang.Thread.run(Thread.java:748)
    t tags	   	logstash
    t thread_name	   	DefaultDispatcher-worker-7 @call-handler#3553
    m
    r
    • 3
    • 13
  • g

    Gus

    09/08/2020, 4:33 PM
    Hello. Ktor/Kotlin newbie here. I'm writing a client for an API and my client is wrapping Ktor in such a way that I can replace its engine with a
    MockEngine
    for testing. However, I'm finding myself duplicating the config (e.g.,
    install(...)
    ) across the two clients because I couldn't find a way to define it once. Any pointers on how one may do that?
    c
    • 2
    • 3
  • i

    Ivann Ruiz

    09/08/2020, 7:44 PM
    For anybody experiencing freezing issues with Ktor for iOS it looks like version
    1.4.0
    is broken. I used version
    1.3.2-1.4.0-rc
    and it worked like a charm as suggested here. Had this issue since last week and after a few days finally found the cause haha thought I'd save others the time. For the record, my iOS app was throwing a
    Thread 1: signal SIGABRT
    on the IDE and saw this in the logs
    Uncaught Kotlin exception: kotlin.native.concurrent.InvalidMutabilityException: mutation attempt of frozen kotlinx.coroutines.ChildHandleNode@31dca08
    . Again it all works now after reverting the versions.
    e
    • 2
    • 6
  • f

    fkrauthan

    09/08/2020, 8:23 PM
    Anyone of the ktor team online? I have a problem with ktor-clients and generics as body of my API call. You can see the failure (and a sample project to quickly reproduce it) here: https://github.com/fkrauthan/ktor-client-issue/blob/master/src/main/kotlin/main.kt Please let me know which bug tracker I should submit this issue to?
    c
    • 2
    • 3
  • j

    John O'Reilly

    09/10/2020, 9:33 AM
    Anyone have experience running ktor-server on Android using sslConnector? Tried to use AndroidKeyStore without luck. (stack trace in thread)
    e
    c
    • 3
    • 12
  • o

    Oleg Yukhnevich

    09/10/2020, 11:07 AM
    Am I only one, who has that issue? https://youtrack.jetbrains.com/issue/KTOR-960
    e
    • 2
    • 9
  • c

    Constantin Muraru

    09/11/2020, 9:21 AM
    Hey folks! We’re trying to log the request payload (using
    CallLogging
    and
    DoubleReceive
    ):
    install(DoubleReceive)
    
    install(CallLogging) {
        level = <http://Level.INFO|Level.INFO>
        format { callFormatterAsCurlCommand(it) }
    }
    
    fun callFormatterAsCurlCommand(call: ApplicationCall): String {
        val payload = runBlocking { call.receiveText() }
        return payload
    }
    However, we receive the
    Request body has been already consumed
    error, which is rather unexpected. Furthermore, the error is thrown by the
    DoubleReceive.kt
    class itself. The docs even say:
    All the receive methods consume the whole payload sent by the client so an attempt to receive a request body twice will lead to 
    RequestAlreadyConsumedException
     error unless you have DoubleReceive feature installed.
    https://ktor.io/servers/calls/requests.html#receiving-several-times
    Exception:
    io.ktor.request.RequestAlreadyConsumedException: Request body has been already consumed (received).
    	at io.ktor.features.DoubleReceive$Feature$install$1.invokeSuspend(DoubleReceive.kt:93) ~[ktor-server-core-jvm-1.4.0.jar:1.4.0]
    	at io.ktor.features.DoubleReceive$Feature$install$1.invoke(DoubleReceive.kt) ~[ktor-server-core-jvm-1.4.0.jar:1.4.0]
    	at io.ktor.util.pipeline.SuspendFunctionGun.loop(PipelineContext.kt:323) ~[ktor-utils-jvm-1.4.0.jar:1.4.0]
    Any tips gladly appreciated.
    t
    • 2
    • 1
  • l

    LastExceed

    09/11/2020, 12:54 PM
    how do i stop a ServerSocket from listening so other applications can listen on the same port? i tried
    .close()
    and
    .dipose()
    but the port is still in use afterwards
    s
    • 2
    • 1
  • i

    Ivan Pavlov

    09/12/2020, 4:45 AM
    Hello guys, I'm getting strange error using ktor-serialization:1.4.0
    kotlinx.serialization.json.internal.JsonDecodingException: Unexpected JSON token at offset 15: Expected '[, kind: SEALED'
    JSON input: {
        "place":{
            "type":"point",
            "lon":22.0,
            "lat":56.7
        }
    }
    Routing looks like that:
    post("/") {
      val body = call.receive<AddVisitDataDto>()
      call.respond(body.toString())
    }
    My model:
    @kotlinx.serialization.Serializable
    data class AddVisitDataDto(
        val place: PlaceDto
    )
    
    @kotlinx.serialization.Serializable
    sealed class PlaceDto {
        @kotlinx.serialization.Serializable
        @SerialName("external")
        data class External(val externalId: String) : PlaceDto()
        @kotlinx.serialization.Serializable
        @SerialName("point")
        data class Point(val lon: Double, val lat: Double) : PlaceDto()
    }
    When I change receiving to the following code it works fine:
    val text = call.receiveText()
    val body = Json.decodeFromString<AddVisitDataDto>(text)
    I tried to add
    @Polymorphic
    to
    place
    property but it only changes error to
    kotlinx.serialization.json.internal.JsonDecodingException: Unexpected JSON token at offset 15: Expected '[, kind: OPEN'
    Am I doing something wrong?
    • 1
    • 1
  • a

    Avadhut

    09/12/2020, 5:55 PM
    open class SimpleJWT(val secret: String) {
        private val algorithm = Algorithm.HMAC256(secret)
        val verifier = JWT.require(algorithm).build()
        fun sign(name: String): String = JWT.create().withClaim("name", name).sign(algorithm)
    }
    fun Application.module() {
        val simpleJwt = SimpleJWT("my-super-secret-for-jwt")
        install(Authentication) {
            jwt {
                verifier(simpleJwt.verifier)
                validate {
                    UserIdPrincipal(it.payload.getClaim("name").asString())
                }
            }
        }
        // ...
    }
    p
    • 2
    • 4
  • k

    keishi kubo

    09/14/2020, 4:41 PM
    How to run ktor project without IDE “run” button ??
    ▶️ 1
    g
    b
    • 3
    • 2
  • k

    Kris Wong

    09/14/2020, 5:27 PM
    any chance this get's looked at soon: https://youtrack.jetbrains.com/issue/KTOR-973? it's blocking my work on all projects using Ktor.
    h
    • 2
    • 2
  • t

    Thiyagu

    09/15/2020, 8:44 AM
    any plan to look at this issue in the upcoming releases: https://youtrack.jetbrains.com/issue/KTOR-356? It's now blocking for our projects with Ktor
    • 1
    • 1
  • s

    Slackbot

    09/15/2020, 12:22 PM
    This message was deleted.
    k
    d
    • 3
    • 19
  • a

    arnaud.giuliani

    09/16/2020, 7:02 AM
    Hi There, I’m Arnaud, the #koin project lead maintainer. Koin is proposing an easy DI solution for Kotlin apps. We already have some ktor features available (https://github.com/InsertKoinIO/koin/blob/master/koin-projects/examples/hello-ktor/src/main/kotlin/org/koin/sample/KtorApplication.kt). If you believe we can work on interesting features for Ktor, let me know. We already bring many stuff for the Android community. 👋
    👍 6
    😊 1
    👏 2
    j
    s
    +2
    • 5
    • 7
  • t

    Thomas

    09/16/2020, 8:05 AM
    Could someone look into the following pull request, please? I need this feature for my project and it would be really great if this could be merged. https://github.com/ktorio/ktor/pull/1258
    e
    • 2
    • 8
  • h

    hhariri

    09/16/2020, 12:45 PM
    An update regarding docs and samples migration https://blog.jetbrains.com/ktor/2020/09/16/docs-and-samples-migration/
    👍 5
    j
    t
    • 3
    • 4
  • j

    John O'Reilly

    09/16/2020, 12:53 PM
    I've setup
    digest
    auth for ktor client and server....REST api requests are working fine but getting 401 for websocket connection......for
    basic
    auth I was able to use
    sendWithoutRequest = true
    but that doesn't seem to be an option for
    digest
    .....is there any way for it to use same auth in that case for ws/wss connections?
    • 1
    • 1
  • j

    Justin Moy

    09/16/2020, 10:13 PM
    Hey. I’m on ktor
    1.4
    and I’m trying to read an arbitrary response back from the ktor http client and return it from my ktor server, but I’m having trouble as the type that could be returned back might change (e.g. I can’t pin it down to
    <http://httpClient.post|httpClient.post><SpecificType>()
    ) is there a way to return an arbitrary type? Also right now my code seems to not be passing forward the return type of the httpClient to the server. Code in thread ->
    • 1
    • 2
  • j

    John O'Reilly

    09/17/2020, 1:50 PM
    Should it be possible to use (server side of) jwt auth on Android?
    • 1
    • 4
  • o

    Oleg Yukhnevich

    09/17/2020, 6:33 PM
    @e5l will performance of native ktor-io will be improved sometime in near future ? Now it's ~ 10 times slower than on jvm Or do you know, is it related to slow native runtime, or because of heavy atomics usage on native, or smth else?
    j
    e
    • 3
    • 5
  • p

    pascal_le_merrer

    09/18/2020, 9:00 AM
    Hello. Since the update of the website, the documentation displayed is the doc for 1.4, with a warning. How may I access the 1.3 doc?
    e
    • 2
    • 1
  • g

    gotoOla

    09/18/2020, 9:37 AM
    Does anyone know how to configure default timeouts on the ktor-client when using OkHttp as an engine? E.g.
    HttpClient(OkHttp) {
                    expectSuccess = false
                }.config {
                    // These value exists in the java builder of OkHttp but I don't know how to configure them through the engine {} or config {} ktor api
                    callTimeout = 0
                    connectTimeout = 0
                    readTimeout = 0
                    writeTimeout = 0
                    pingInterval = 0
                }
    r
    • 2
    • 3
Powered by Linen
Title
g

gotoOla

09/18/2020, 9:37 AM
Does anyone know how to configure default timeouts on the ktor-client when using OkHttp as an engine? E.g.
HttpClient(OkHttp) {
                expectSuccess = false
            }.config {
                // These value exists in the java builder of OkHttp but I don't know how to configure them through the engine {} or config {} ktor api
                callTimeout = 0
                connectTimeout = 0
                readTimeout = 0
                writeTimeout = 0
                pingInterval = 0
            }
I'm guessing I should use this:
val client = HttpClient() {
    install(HttpTimeout) {
        // timeout config
        requestTimeoutMillis = 1000
    }
}
Looking back at it it was maybe a stupid question... I was used to the apache engine where you configured it in the engine
r

rrva

09/21/2020, 10:09 AM
the requestTimeoutMillis is also broader than the engine-level timeouts, it’s implemented with https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/with-timeout.html (I believe) so it covers all steps of request-processing. For example if DNS resolving is slow is not covered by connectTimeout
but what happens to the resources of requests that are “abandoned” by configuring requestTimeoutMillis I do not know. I hope they are cleaned up immediately
View count: 9