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

    marioled

    08/13/2020, 1:39 PM
    How to read jwt string array claim? Im trying with asList(), but don't know how to call method.
    • 1
    • 1
  • m

    manlan

    08/14/2020, 5:26 AM
    Why is the IDE complaining of blocking call when I'm not specifying the Dispatcher for
    async
    ? (When I am already in the
    context
    of the IO Dispatcher)?
    Untitled
    g
    d
    • 3
    • 21
  • c

    codec

    08/14/2020, 8:09 AM
    How can one differentiate between the
    DefaultWebSocketSession
    objects? For example, in my
    Application.Kt
    class, I have:
    webSocket("/update") {
            connections += this
            try {
                while (true) {
                    when (val frame = incoming.receive()) {
                        is Frame.Text -> {
                            val text = frame.readText()
                            // Send message to all the connections, except the messenger connection.
                            for (conn in connections) {
                                if (conn != this) {
                                    conn.outgoing.send(Frame.Text(text))
                                }
                            }
                        }
                    }
                }
            } catch (e: ClosedReceiveChannelException) {
                <http://log.info|log.info>("connection closed. ignore.")
            }
            finally {
                connections -= this
            }
        }
    }
    So, what I’m trying to accomplish works there, in that class, but not elsewhere in other application classes. When I just have a list of connection objects, or
    DefaultWebSocketSession
    objects?
    w
    • 2
    • 2
  • a

    andylamax

    08/15/2020, 4:46 PM
    How do I upload a file by using
    ktor-client
    in
    multiplatform
    ? I am aware of the
    formData{}
    but I can't seem to find where I can
    append
    a
    file
    to the builder.
    e
    • 2
    • 15
  • n

    Nikky

    08/15/2020, 10:00 PM
    seems like on 1.3.2-1.4.0-rc client-websockets is not published ? was this renamed ?
    e
    • 2
    • 2
  • c

    CestLaVie

    08/15/2020, 11:11 PM
    Hi! What is the most recommended way to generate OpenAPI spec for existed KTOR application? Is there any way like springdoc or springfox in spring?
    👀 5
    s
    • 2
    • 2
  • w

    william

    08/16/2020, 5:17 PM
    anyone have info of the status of native websockets ? looking to use it for a multiplatform project on iOS
    • 1
    • 1
  • a

    andylamax

    08/16/2020, 10:23 PM
    Somehow this,
    install(CORS) {
            method(HttpMethod.Options)
            method(HttpMethod.Patch)
            method(HttpMethod.Delete)
            headersOf(HttpHeaders.AccessControlAllowOrigin, "*")
            headersOf(
                HttpHeaders.AccessControlAllowMethods to listOf(
                    HttpMethod.Get.value,
                    HttpMethod.Post.value,
                    HttpMethod.Put.value,
                    HttpMethod.Patch.value,
                    HttpMethod.Delete.value,
                    HttpMethod.Head.value,
                    HttpMethod.Options.value
                ),
                HttpHeaders.AccessControlAllowHeaders to listOf(
                    HttpHeaders.Origin, HttpHeaders.ContentType, HttpHeaders.XAuthToken
                )
            )
            anyHost()
        }
    Doens't help me when I am trying to fetch to my restful api with
    ktor
    . How do I allow Cross Origin Resource Sharing? I still get
    Access to fetch at '<http://192.168.43.218:8080/v0.1.0/auth/users/exists>' from origin '<http://localhost:8088>' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
    I have tested by disabling the web security. It works, but I don't wanna do that. Can someone please tell me how? Rest Api: ktor-server Client: ktor-client-js Browser: Chromium,Opera
    m
    • 2
    • 2
  • a

    andylamax

    08/17/2020, 12:11 AM
    How do I enable CORS in ktor-server?
    h
    • 2
    • 2
  • p

    phldavies

    08/17/2020, 12:37 PM
    Is there any support for serving a TLS socket using ktor raw sockets? It seems that ktor-network-tls is only for client sockets?
    c
    • 2
    • 1
  • m

    matej

    08/17/2020, 1:02 PM
    Is there any way of doing a streaming upload on iOS yet? Last I checked you could only load the entire file in memory and send the bytes, which is clearly not ideal if files are bigger
    a
    • 2
    • 2
  • d

    David Glasser

    08/17/2020, 9:38 PM
    I’m seeing some weird behavior where I use a ktor client within a
    withContext
    block and the request succeeds but the withContext never hangs. like, i have:
    <http://log.info|log.info>("going to execute request $callsite")
    withContext(MyContextThingy()) {
     <http://log.info|log.info>("in first context")
    }
    <http://log.info|log.info>("back from context")
    val res: HttpResponse = withContext(MyContextThingy()) {
     <http://log.info|log.info>("top of context")
     val response: HttpResponse = httpClient.request {
      url.takeFrom(this@DruidClient.url)
      method = <http://HttpMethod.Post|HttpMethod.Post>
      contentType(ContentType.Application.Json)
      body = req
     }
     <http://log.info|log.info>("after request")
     response
    }
    <http://log.info|log.info>("after WC")
    res
    and it gets in and out of the first withContext fine, and logs
    after request
    , but never
    after WC
    . anyone seen anything odd like this?
    • 1
    • 4
  • a

    andylamax

    08/17/2020, 11:05 PM
    Ktor
    for
    1.4.0
    isn't release yet... E.T.A?
    👍 3
    👀 5
    h
    j
    +4
    • 7
    • 8
  • h

    hhariri

    08/18/2020, 7:26 PM
    <!here> Ktor 1.4.0 has been released! https://blog.jetbrains.com/ktor/2020/08/18/ktor-1-4-0-now-available/
    🕸️ 1
    🤘 4
    👍 4
    🎉 51
    👍🏼 1
    s
    a
    +2
    • 5
    • 6
  • j

    Jabez Magomere

    08/18/2020, 8:07 PM
    Could anyone recommend how i can implement database caching on Ktor? Is there a redis implementation sample or something similar ?
    n
    • 2
    • 2
  • j

    John O'Reilly

    08/18/2020, 8:57 PM
    Using Ktor on client for Kotlin Multiplatform project and getting exception with 1.4 set of libraries when running on iOS with
    native-mt
    kotlinx coroutines (and also updated to
    CIO
    engine as it seems is now required to use this). Following is set of dependencies I'm using (also updated in following branch - https://github.com/joreilly/BikeShare/tree/1.4). (exception in thread....)
    const val kotlin = "1.4.0"
        const val kotlinxCoroutines = "1.3.9-native-mt"
        const val ktor = "1.4.0"
        const val kotlinxSerialization = "1.0.0-RC"
    e
    t
    +2
    • 5
    • 13
  • e

    edenman

    08/19/2020, 12:35 AM
    anybody know why ResponseException.exception was marked Transient? Here’s the commit but the referenced issue# doesn’t exist so I can’t tell the context https://github.com/ktorio/ktor/commit/2ef0a8dec19bec1ceef3d9574adbe3593ad301ae
    • 1
    • 1
  • g

    Gunslingor

    08/19/2020, 1:26 AM
    How do I use node modules in ktor, serve them up? Like instead of this:
    link("/libs/package/css/somepackage.min.css","stylesheet")
    which would be referencing stuff in the resources folder, how do you do something like:
    link(npm("something))
    I haven't really been able to figure out this node thing.
    a
    • 2
    • 27
  • p

    Pere Casafont

    08/19/2020, 10:50 AM
    hi there! Is there a way to unit test embedded servers?
    m
    • 2
    • 2
  • e

    Eric Grimsborn

    08/19/2020, 11:15 AM
    server
    authentication
    oauth
    routing
    I am trying to implement an OAuth code flow. When the flow fails e.g. user does not have access to the app i get a callback with an
    error
    query parameter. When this is the case I do not wish to apply auth. I have this routing:
    route("/login-callback") {
        param("error"){
           handle(errorHandler)
        }
        authenticate("my-oauth") {
            handle(successHandler)
        }
    }
    when running without authentication block it will match the errorHandler but when adding the authentication around successHandler it will run it for errorHandler as well and since the request is not authed it will redirect causing another callback etc. until I get too many redirects error. Is there a way to not run the auth when matching
    param("error")
    above?
    • 1
    • 1
  • j

    jean

    08/19/2020, 12:21 PM
    I’m updating my mpp to 1.4 and get this error now
    Failed to find HTTP client engine implementation in the classpath: consider adding client engine dependency. See <https://ktor.io/clients/http-client/engines.html>
    I notice some changes in the doc, as far as I remember, that page had a comment regarding multiplatform saying devs could just omit to specify an engine when used in mpp context. I guess it’s not the case anymore? I plan to share an api client based on ktor client to android and ios, should I change to something like that :
    class ApiClient(
        private val engine: HttpClientEngine
    ) {
        private val client = HttpClient(engine)
    }
    then android can instantiate this by passing
    CIO
    and iOS passing
    Ios
    e
    r
    +2
    • 5
    • 24
  • w

    wellingtoncosta

    08/19/2020, 2:03 PM
    I’m updating my mpp to 1.4, but now the
    KotlinxSerializer
    isn’t recognized.
    commonMain {
        implementation("io.ktor:ktor-client-core:1.4.0")
        implementation("io.ktor:ktor-client-json:1.4.0")
        implementation("io.ktor:ktor-client-logging:1.4.0")
        implementation("io.ktor:ktor-client-serialization:1.4.0")
    }
    ➕ 3
    t
    • 2
    • 6
  • k

    Kepha

    08/20/2020, 7:50 AM
    In kotlin project, we can set different package name with source folder path: Can I disable this and package name which is different with folder path gotten Red Syntax Error ?
    d
    • 2
    • 3
  • j

    Javier

    08/21/2020, 12:00 PM
    Is it possible to wrap the model of a response with another custom model via custom feature? Is there a similar feature created to take a look to it?
    client.get<MyWrapper<SomeModel>>(...)
    n
    • 2
    • 6
  • j

    John O'Reilly

    08/21/2020, 6:18 PM
    Is there any way right now to use Ktor 1.4 with Kotlin/Native? https://youtrack.jetbrains.com/issue/KTOR-915 seems to indicate you can work around by forcing use of
    1.3.8-native-mt-1.4.0-rc
    of kotlinx coroutines but that's not working for me here at least.
    r
    • 2
    • 24
  • p

    pascal_le_merrer

    08/22/2020, 7:54 AM
    Hello. I managed to set up JWT authentication in ktor. It works. However I dont see how to get the claims containd in the token when processing a request. How can I get them?
    p
    • 2
    • 8
  • z

    zero_coding

    08/22/2020, 9:54 AM
    What is the best practice to abstract out the body handler?
    j
    e
    • 3
    • 6
  • m

    max.cruz

    08/23/2020, 6:48 AM
    Hello. I’m updating to kotlin and ktor 1.4.0 but
    ktor-client-core-native
    is not available yet. Is there an alternative repository?
    a
    r
    • 3
    • 9
  • m

    Marcin Bak

    08/24/2020, 12:29 AM
    Trying out ktor websockets on Android. Maybe someone encountered a case I have: the sending of messages works however when I try to receive messages I get an exception
    java.io.EOFException
            at okio.RealBufferedSource.require(RealBufferedSource.kt:201)
            at okio.RealBufferedSource.readByte(RealBufferedSource.kt:210)
            at okhttp3.internal.ws.WebSocketReader.readHeader(WebSocketReader.kt:119)
            at okhttp3.internal.ws.WebSocketReader.processNextFrame(WebSocketReader.kt:102)
            at okhttp3.internal.ws.RealWebSocket.loopReader(RealWebSocket.kt:293)
            at okhttp3.internal.ws.RealWebSocket$connect$1.onResponse(RealWebSocket.kt:195)
            at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:504)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
            at java.lang.Thread.run(Thread.java:818)
    my setup is simple
    val commonMain by getting {
                dependencies {
                    implementation(kotlin("stdlib-common"))
                    implementation(project(":backend-frontend-shared"))
                    implementation("io.ktor:ktor-client-core:$ktor_version")
                    implementation("io.ktor:ktor-client-websockets:$ktor_version")
                    implementation("io.ktor:ktor-client-serialization:$ktor_version")
                    implementation("io.ktor:ktor-client-logging:$ktor_version")
                }
            }
            val androidMain by getting {
                dependencies {
                    implementation(kotlin("stdlib"))
                    implementation("io.ktor:ktor-client-websockets-jvm:$ktor_version")
                    implementation("io.ktor:ktor-client-serialization-jvm:$ktor_version")
                    implementation("io.ktor:ktor-client-okhttp:$ktor_version")
                    implementation("io.ktor:ktor-client-logging-jvm:$ktor_version")
                }
            }
    and I read from websocket like this:
    HttpClient {
                install(WebSockets)
            }.ws(
                method = HttpMethod.Get,
                host = "192.168.0.38",
                port = 8080,
                path = CHAT_WS_PATH
            ) {
                try {
                    val frame = incoming.receive()
                } catch (e: Exception) {
                    //" Here's the crash
                }
            }
    • 1
    • 1
  • h

    hikkidev

    08/24/2020, 8:40 AM
    What has changed in feature
    HttpCallValidator
    in v1.4.0 ? DoubleReceiveException
    val client = HttpClient(OkHttp) {
            expectSuccess = false        
            
            install(HttpCallValidator) {
                validateResponse { response ->  throw RuntimeException("Response not valid") }
            }
    }
    
    @Throws(RuntimeException::class) 
    suspend fun myBestRequest(): MyResponseObj = client.get {...}
    Why can't I catch the error? In version 1.3.2 this worked.
    try {
            val response = myBestRequest()
            Result.success(response)
    } catch (cause: Throwable) {
            Result.failure(cause)
    }
    c
    e
    • 3
    • 3
Powered by Linen
Title
h

hikkidev

08/24/2020, 8:40 AM
What has changed in feature
HttpCallValidator
in v1.4.0 ? DoubleReceiveException
val client = HttpClient(OkHttp) {
        expectSuccess = false        
        
        install(HttpCallValidator) {
            validateResponse { response ->  throw RuntimeException("Response not valid") }
        }
}

@Throws(RuntimeException::class) 
suspend fun myBestRequest(): MyResponseObj = client.get {...}
Why can't I catch the error? In version 1.3.2 this worked.
try {
        val response = myBestRequest()
        Result.success(response)
} catch (cause: Throwable) {
        Result.failure(cause)
}
https://youtrack.jetbrains.com/issue/KTOR-608 or is it different?
c

cy

08/24/2020, 12:22 PM
cc @e5l
e

e5l

08/24/2020, 12:42 PM
Yep, it's the same. I'll take a look
View count: 2