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

    Vladislav Areshkin [IceRock]

    10/08/2021, 1:11 PM
    Hello! Can anybody tell is there a way to receive a body of one response twice to avoid
    DoubleReceiveException
    in ktor-client? Or maybe there are ways to create some kind of feautre/plugin that receives the body at the
    HttpReceivePipeline.After
    phase, processes the body data and after continues piplene execution unchanged for the response? Is it possible?
    ✅ 1
    e
    r
    7 replies · 3 participants
  • j

    jdiaz

    10/08/2021, 6:03 PM
    Is it possible to edit the features of an already instantiated client? I'm seeing it returns a new instance when using client.config{} but I would like to retain the same object instance
    1 reply · 1 participant
  • n

    nilTheDev

    10/09/2021, 5:02 PM
    I am confused between the server engines that are available in Ktor. Netty seems the default choice but CIO is something that uses coroutines in its core. Should I use CIO? Would there be any API level difference? I mean the way I use Ktor? What would be some benefits that I can get by choosing CIO over Netty?
    b
    i
    +1
    9 replies · 4 participants
  • s

    Skovisen

    10/09/2021, 7:58 PM
    Does anyone know of a good way to incorporate the
    run
    task with development mode set to
    true
    and the
    build -t
    task into a single gradle task?
    a
    2 replies · 2 participants
  • n

    nilTheDev

    10/10/2021, 3:53 AM
    I never deployed a REST Api on a real server. I am wondering how TLS get implemented. I read that a lot of crazy stuff go on in TLS handshake. It includes asymmetrical encryption (RSA), Diffie-Hellmen Key Exchange and many other things as well. I am wondering how hard it actually is to implement on the backend? Are all things done manually?
    c
    c
    +2
    5 replies · 5 participants
  • h

    hhariri

    10/11/2021, 11:32 AM
    📣 📣 📣 Folks, we have a question around 2.0. Is anyone using any of the EAPs for it? And if so, any major issues you’ve encountered?
    :yes: 1
    🇳🇴 2
    e
    3 replies · 2 participants
  • t

    Tim Malseed

    10/12/2021, 7:39 AM
    If I wanted to implement some kind response mapper, where I wrap an already-deserialized response object, with some details about the actual HttpResponse itself, how would I go about doing that? It seems like a response pipeline interceptor of some kind. I had a read of the docs, but it wasn't obvious to me what this would look like
    a
    4 replies · 2 participants
  • f

    FadiBouteraa

    10/12/2021, 9:50 AM
    #ktor help me 🙏 how to apply ssl pinning in ktor mobile
    a
    1 reply · 2 participants
  • a

    altavir

    10/12/2021, 1:37 PM
    I just got an unexpected problem. I try to use raw sockets from ktor-network to work with home-made TCP-based protocol. And I can't see how I can use Input/Output API with it. It seems like socket IO lives in a completely different world. For example, instead WritableByteChannel I have ByteWriteChannel, which seems to be unrelated. The problem is that I already have ktor-io based code that work with files and it would be very sad to have to re-do it for Ktor sockets. Are there any solutions to this?
    e
    20 replies · 2 participants
  • m

    mirland

    10/12/2021, 7:14 PM
    Hey 👋, I'm facing CORS issues using Ktor client for Kotlin JS. I'm know it's not an issue in ktor side, but I'm trying to find a solution.
    Access to fetch at '<https://myserver/api/v1/csrf>' from origin '<http://localhost:8080>' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
    I want to know if it's possible to use a reverse proxy in KotlinJs client. I tried to setup a proxy, in the engine setup, but it's not supported for JS. Basically, I need to do something like this (this is how I solve my issue using react) . Do you know how can do something similar using ktor? Or do you know some alternative? Thanks!
    s
    a
    +1
    9 replies · 4 participants
  • t

    tim

    10/13/2021, 9:32 AM
    hello, is there a way to get ktor to log out all configured routes at startup?
    a
    2 replies · 2 participants
  • s

    Simran Preet Singh Narang

    10/13/2021, 5:19 PM
    Has anyone used JPA with Ktor and how was your experience?
    👀 1
    h
    1 reply · 2 participants
  • j

    jean

    10/14/2021, 7:05 AM
    I have the following json :
    private val jsonResponse = """
            {
              "offset": 0,
              "limit": 20,
              "available": 104,
              "items": [
                {
                  "type": "news type",
                  "title": "news title",
                  "image": "news image",
                  "link": "news link",
                  "date": "1621807201000"
                }
              ]
            }
        """.trimIndent()
    When I parse it manually with
    Json.decodeFromString<NewsList>(jsonResponse)
    I get my
    NewsList
    object without any issues, but when I run my unit test with a
    MockEngine
    returning the json as a string for any request, I end up with the following error :
    kotlinx.serialization.json.internal.JsonDecodingException: Expected start of the array '[', but had 'EOF' instead
    JSON input: .....ink": "news link",
          "date": "1621807201000"
        }
      ]
    }
    What am I doing wrong here?
    a
    d
    11 replies · 3 participants
  • j

    John Pali

    10/15/2021, 12:19 PM
    Hi people, kinda new here... was wondering how can I accept a JSON payload in Ktor tried
    call.receiveText()
    but it gets is to a string - had a look on the docs about serialization, but got quite confused there.
    b
    m
    +1
    14 replies · 4 participants
  • j

    John Pali

    10/15/2021, 8:56 PM
    Hi guys, anybody has an idea how can I get the current authenticated user in my service layer? something similar to
    SecurityContextHolder
    in spring?
    b
    a
    2 replies · 3 participants
  • b

    Benoye

    10/18/2021, 11:24 AM
    Hi guys ! I am using the ktor client
    Auth
    capability for JWT tokens on iOS and Android apps. I encountered a case on iOS where I have two concurrent calls to my JWT-based API with no pre-existing token Only one of both calls is retried after the
    requestToken()
    and that call effectively succeeds, the other is not retried.. This is not critical but if anyone happens to know what is going on, I am interested 😉
    a
    1 reply · 2 participants
  • s

    Stefan Oltmann

    10/18/2021, 12:53 PM
    I have trouble understanding how to do OAuth in my client. Following the sample from https://ktor.io/docs/auth.html I can get my user info once, but if I try to reuse the authorizationCode I get an
    invalid_grant
    I guess I need to save the accessToken, correct? Does someone have a demo how to do proper OAuth with Ktor?
    h
    a
    28 replies · 3 participants
  • d

    David Nault

    10/18/2021, 6:23 PM
    Any tips or best practices for handling unsolicited responses when using raw sockets in a client? In other words, ktor makes it really easy to have a single coroutine send a request and read the response, but how should the code / coroutines be structured to allow for the server sending "responses" that don't have a corresponding client request? I'm assuming the client will need to read and write in separate coroutines and somehow correlate the requests and responses, but I'm wondering if there's a cleaner solution.
    d
    14 replies · 2 participants
  • s

    Stefan Oltmann

    10/19/2021, 3:50 PM
    The official OAuth client sample is so bad... I get a lot of
    This API is internal in ktor and should not be used. It could be removed or changed without notice.
    warnings for this
    append
    calls. 😕 https://github.com/ktorio/ktor-documentation/blob/0f2ef73cdc4fce483c2ee8e15c8995e6[…]nt-auth-oauth-google/src/main/kotlin/com/example/Application.kt
    d
    1 reply · 2 participants
  • a

    arthur_sav

    10/19/2021, 4:10 PM
    I was looking at the
    ktor + docker
    documentation which i found a bit incomplete. In particular, the suggested Dockerfile is this
    FROM openjdk:8-jdk
    EXPOSE 8080:8080
    RUN mkdir /app
    COPY ./build/install/docker/ /app/
    WORKDIR /app/bin
    CMD ["./docker"]
    However, ``./gradlew installDist`` has to be run manually before running docker which seems rather odd considering most use cases are deployment on the cloud. So here is an improved version that just runs without additional steps (builds both the source & docker image)
    FROM gradle:6-jdk8 AS build
    COPY --chown=gradle:gradle . /home/gradle/src
    WORKDIR /home/gradle/src
    RUN gradle installDist --no-daemon
    
    FROM openjdk:8-jdk
    EXPOSE 8080:8080
    RUN mkdir /app
    COPY --from=build /home/gradle/src/build/install/docker/ /app/
    WORKDIR /app/bin
    CMD ["./docker"]
    Also, naming the project
    docker
    … could be confused with running docker itself.
    a
    g
    2 replies · 3 participants
  • s

    spierce7

    10/19/2021, 8:22 PM
    Why does auto-reload work when do
    embeddedServer(
            factory = Netty,
            port = 8080,
        ) {
            modules()
        }
    But not
    embeddedServer(
            factory = Netty,
            port = 8080,
            module = Application::modules
        )
    a
    4 replies · 2 participants
  • h

    Hexa

    10/19/2021, 8:32 PM
    is the
    return@get
    required here or can it can remove?
    route("/test") {
                get {
                    try {
                         // some logic
                        call.respond(HttpStatusCode.OK)
                    }  catch (e: Exception) {
                         return@get call.respond(HttpStatusCode.InternalServerError) // here
                    }
                }
    r
    1 reply · 2 participants
  • l

    Landry Norris

    10/19/2021, 9:53 PM
    When I run my tests, Ktor throws an exception: "io.ktor.features.UnsupportedMediaTypeException: Content type / is not supported". I have installed Serialization, and it handles application/json, but not all of my endpoints take in a json. Is there something I'm missing, or is this a Ktor bug?
    a
    2 replies · 2 participants
  • z

    Zhiqiang Bian

    10/20/2021, 11:06 AM
    Hi everyone, I am using ktor client for a KMM project. And I have installed the ktor
    logging
    feature. Does anyone know how to match an HTTP request to the corresponding response in the logs? Assuming I send 10 http requests to the backend immediately. And then, I should receive 10 responses. But I cannot tell which response belongs to which request from the logs. Is it possible to assign a UUID to each request and its corresponding responses, then we can match them in the logs easily? Or it must involve some changes on the backend too? For example, the frontend generates a UUID in the header, and backend use the same one in the response header? ----------------------------------------------------------- I assume that in the responsePipeline receives each response in the same order of the requestPipeline. But I am not sure if it is correct. So my temporal solution is to modify the
    Logging
    class (since it does not allow extends). I added two Int variables
    requestSequenceId
    and
    responseSequenceId
    . Every time the
    logRequest
    and
    logResponse
    get called, I just plus 1 for each sequenceId.
    private var requestSequenceId: Int = 0
    private var responseSequenceId: Int = 0
    ...
    private suspend fun logRequest(request: HttpRequestBuilder): OutgoingContent? {
            if (<http://level.info|level.info>) {
                logger.log("REQUEST SEQUENCE ID: ${requestSequenceId++}")
    ...
    private fun logResponse(response: HttpResponse) {
            if (<http://level.info|level.info>) {
                logger.log("RESPONSE SEQUENCE ID: ${responseSequenceId++}")
    i
    a
    6 replies · 3 participants
  • b

    Bert Heyman

    10/21/2021, 9:39 AM
    Hey all! New to this space 🙂 I’m learning Kotlin with a PHP / Laravel background. Covered the basics and these make sense. As a next step, I’m looking into Ktor and Exposed. This tutorial helped me with Ktor: https://ktor.io/docs/creating-http-apis.html Next step would be to include Exposed in there as well, using their getting started: https://github.com/JetBrains/Exposed/wiki/Getting-Started#download Coming from a different background, I feel I miss some background on the installation process and frameworks so feeling a little lost there. It’s hard to assess resources I found, as they refer to different Kotlin/Ktor versions and I’m not so sure what’s still up to date (enough) and what is not. Any tips on what I could read into to get a better grasp? TL;DR: how can I properly install Exposed in Ktor?
    a
    d
    3 replies · 3 participants
  • v

    Vinay Pothnis

    10/22/2021, 4:59 PM
    Hello KTor Team! I wanted to check with on couple of things related to
    ktor-client
    and the best practices around it. 1. Whats the right way to re-use connections (or use a connection pool) with
    CIOEngine
    ? I am using the following configs:
    engine {
        maxConnectionsCount = 250
        pipelining = true
        endpoint {
          maxConnectionsPerRoute = 100
          pipelineMaxSize = 20
          keepAliveTime = 5000
          connectTimeout = 5000
          connectAttempts = 5
          threadsCount = 20
        }
      }
    It looks like without the
    pipielining = true
    flag, new connections were being created for every request/call. Are these sufficient or is there any other config that I would need to set to effectively re-use connections? 2. Whats the recommended way to use
    client.close()
    or
    client.use {}
    - Especially when we are sharing/re-using the
    HttpClient
    I went through the docs here - https://ktor.io/docs/client.html#close-client With a shared
    HttpClient
    - if I used
    client.use {}
    - i was seeing errors on subsequent requests after some initial successful requests. Errors like -
    kotlinx.coroutines.JobCancellationException: Parent job is Completed; job=JobImpl{Completed}@5e4f8454
    So, when should this actually be used? During shutdown to release/cleanup the resources? Thanks so much for your help with this!
    a
    e
    +1
    10 replies · 4 participants
  • c

    Charles Jo

    10/22/2021, 6:17 PM
    Hi! Is there any solution to build SSL websocket server with ktor in Android? Here I think Android is not main point. Main point is that how I can implement SSL websocket server with ktor. Thanks.
    a
    3 replies · 2 participants
  • c

    Charles Jo

    10/22/2021, 9:40 PM
    Hi Ktor Team! This is another question. How can I check ktor embeddedserver's status? For example, before start the server I want to check if the server is alive or not. Is there any solution? Thanks.
    b
    5 replies · 2 participants
  • t

    Tobias Marschall

    10/23/2021, 5:47 PM
    Hi there, how am i supposed to launch coroutines in a request handler? I want to instantly respond to the client and handle the request in the background using a coroutine. I tried to do it this way and it also works, but when i extract the request handler into an extra function, then intellij gives me a justified warning. No warning:
    get("/test") {
        launch {
            // do something
        }
    
        call.respond("Success")
    }
    Warning
    Ambiguous coroutineContext due to CoroutineScope receiver of suspend function
    when using:
    suspend fun PipelineContext<Unit, ApplicationCall>.handleTest() {
        launch {
            // do something
        }
    
        call.respond("Success")
    }
    
    get("/test") {
        handleTest()
    }
    How am i supposed to do this?
    h
    d
    +2
    18 replies · 5 participants
  • m

    Mustafa Ozhan

    10/25/2021, 12:59 PM
    Hello what is the consequences of increasing
    requestQueueLimit
    ? The default is 16. I started to have crashes in my clients
    Caused by java.net.ConnectException
    and I believe only logical explanation is having so much call in the queue: https://stackoverflow.com/a/6876306/8334146
    s
    a
    3 replies · 3 participants
Powered by Linen
Title
m

Mustafa Ozhan

10/25/2021, 12:59 PM
Hello what is the consequences of increasing
requestQueueLimit
? The default is 16. I started to have crashes in my clients
Caused by java.net.ConnectException
and I believe only logical explanation is having so much call in the queue: https://stackoverflow.com/a/6876306/8334146
s

spand

10/25/2021, 1:14 PM
You can configure this yourself
m

Mustafa Ozhan

10/25/2021, 1:15 PM
Yeap I found out that but my question what are the consequences of increasing it ? I am just not sure how much I should increase like 16 to 20 or 16 to 32 …
a

Aleksei Tirman [JB]

10/25/2021, 5:53 PM
As far as I understand, this limit determines the max number of running call handlers that process requests in a single socket connection.
👆 1
View count: 3