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

    Jakub Gwóźdź

    09/06/2022, 9:44 AM
    Hi there. What is the preferred way of mocking ApplicationCall? I don’t want to create whole
    testApplication { … }
    , but I have a method that is simply
    suspend fun readPartsContents(call: ApplicationCall): List<UploadedContent> = call
        .receiveMultipart()
        .readAllParts()
        .flatMap(::processPart)
    and I’d like to mock that
    call
    in my unit test. But I can’t since
    .receiveMultipart()
    is unmockable extension function…
    • 1
    • 1
  • h

    hhariri

    09/07/2022, 5:47 AM
    📣 Ktor 2.1.1 released! https://ktor.io/changelog/2.1/ 📣
  • a

    Ayfri

    09/08/2022, 7:46 AM
    Hi, what plugin should I use to have code completion for my
    application.conf
    file ? I have the
    ktor
    plugin but it shows very little syntax highlighting and no real code completion ? (just the words I already used in the file)
    s
    b
    • 3
    • 2
  • h

    Hamza GATTAL

    09/08/2022, 3:24 PM
    In Ktor client How does the
    DefaultRequest
    plugin work with
    WebSockets
    .
    a
    • 2
    • 1
  • i

    Ivan Đorđević

    09/08/2022, 5:33 PM
    Hi, Why isn't there a nullable variant of
    @JvmName("postTyped")
    public inline fun <reified R : Any> <http://Route.post|Route.post>(
        crossinline body: suspend PipelineContext<Unit, ApplicationCall>.(R) -> Unit
    ): Route = post {
        body(call.receive())
    }
    ? I realize there's
    receiveNullable
    but there's no way to do it via route declaration, only in the body of the route itself 😕 EDIT: Nvm I realize I'm just stupid, I could just make properties inside the route model nullable instead to achieve the same effect :D
    h
    • 2
    • 1
  • f

    Francesco Di Sciascio

    09/09/2022, 8:16 AM
    hi everyone
  • f

    Francesco Di Sciascio

    09/09/2022, 8:18 AM
    I am looking for a function that manages programmatically the parameters in a GET, to create DB queries dynamically. At the moment, i have the following:
    route("/sCap"){
        val dao: DAOFacade = DAOFacadeImpl()
        get{      
            val codiceParam = call.request.queryParameters["codice"]
            val listSCap = dao.allSCapFiltered(codiceParam)
            if(listSCap.isEmpty())
                call.respondText("Nessun elemento trovato", status = HttpStatusCode.NotFound)
            else
                call.respond(listSCap)
        }
    ...
    }
    and in the DAO:
    override suspend fun allSCapFiltered(codice: String?): List<SCap> {
        return if(codice.isNullOrEmpty()){
            DatabaseFactory.dbQuery {
                S_Cap.selectAll().map(::resultRowToSCap)
            }
        } else {
            DatabaseFactory.dbQuery {
                S_Cap
                    .select { S_Cap.codice like "%$codice%" }
                    .map(::resultRowToSCap)
            }
        }
    }
    is there a way to manage all the parameters expected dynamically, based on properties of data class?
    data class SCap(val idcap: Int?,
                        val regione: String?,
                        val prov: String?,
                        val comune: String?,
                        val cap: Int?,
                        val codice: String?
                        )
    Thanks everyone for suggestions!
    a
    • 2
    • 7
  • l

    Lucas León

    09/10/2022, 5:08 AM
    I would appreciate some help with this issue I posted on Youtrack https://youtrack.jetbrains.com/issue/KTOR-4865/Receiving-null-body-after-HttpResponseValidator-is-executed
    a
    • 2
    • 7
  • h

    Hamza GATTAL

    09/10/2022, 2:29 PM
    Ktor support STOMP??
    t
    • 2
    • 1
  • a

    aarjav

    09/10/2022, 6:21 PM
    Hey, I want to create a client library for opensearch that takes advantage of kotlin features to provide a better DSL than a pure java library. For it, I am considering using ktor as the http client library. Is there any guidance on the best practices / do's & don'ts of writing such client libraries? Or perhaps another client library which "does it well"? Some things like using different dispatchers or not, ways of allowing user to configure the internals, other things I need to consider etc.
  • z

    zt

    09/12/2022, 1:09 AM
    How can I write a unsigned 16 bit int to the send channel in a unix socket connection? There's
    writeShort
    but that's for signed int
    e
    • 2
    • 5
  • r

    Raphael TEYSSANDIER

    09/12/2022, 2:10 PM
    Hello, how can I know in local if I’m in debug mode or not ?
    s
    a
    • 3
    • 5
  • b

    Ben Kosten

    09/12/2022, 3:11 PM
    Hey guys, I'm currently trying to write a TCP proxy with KTor, however I'm having some trouble reading from one
    ByteReadChannel
    and copying those bytes over and Writing to another
    ByteWriteChannel
    The proxy should tunnel connections from client A to server B via proxy server C like so:
    A <---> C <---> B
    currently, I have something like the following:
    //some boilerplate to open correct channels and establish socket connections
    val clientReadChannel = clientSocket.openReadChannel()
    val clientWriteChannel = clientSocket.openWriteChannel(true)
    
    val serverReadChannel = serverSocket.openReadChannel()
    val serverWriteChannel = serverSocket.openWriteChannel(true)
    
    launch(<http://Dispatchers.IO|Dispatchers.IO>) {
        clientReadChannel.copyTo(serverWriteChannel)
    }
    
    launch(<http://Dispatchers.IO|Dispatchers.IO>) {
        serverReadChannel.copyTo(clientWriteChannel)
    }
    a
    • 2
    • 7
  • z

    zt

    09/12/2022, 11:10 PM
    I'm having some trouble figuring out what I'm doing wrong in my code using sockets to communicate with the X window system protocol
    val selectorManager = SelectorManager(Dispatchers.Main)
    val socketPath = "/tmp/.X11-unix/X2"
    val tcp = aSocket(selectorManager).tcp()
    val clientConnection = try {
        tcp.connect(UnixSocketAddress(socketPath))
    } catch (e: Exception) {
        selectorManager.close()
        println(e.message)
        exitProcess(1)
    }
    
    val readChannel = clientConnection.openReadChannel()
    val sendChannel = clientConnection.openWriteChannel()
    
    val authName = ""
    val authData = ""
    
    fun BytePacketBuilder.writePadding(bytes: Int) {
        repeat((4 - bytes % 4) % 4) { writeByte(0) }
    }
    
    sendChannel.writePacket {
        writeUByte(102u)
        writeByte(0)
        writeUShort(11u)
        writeUShort(0u)
        writeUShort(authName.length.toUShort())
        writeUShort(authData.length.toUShort())
        writeByte(0)
        writeText(authName)
        writePadding(authName.length)
        writeText(authData)
        writePadding(authData.length)
    }
    
    sendChannel.flush()
    
    println(readChannel.readByte())
    It just suspends at the readByte call
    r
    • 2
    • 2
  • n

    napperley

    09/13/2022, 1:50 AM
    How do I setup static routing with the Native version of Ktor Server? I tried doing the following to setup static routing:
    // ...
        static("/") {
            staticRootFolder = File("files")
            file("index.html")
            default("index.html")
            static("assets") {
                files("css")
                files("js")
            }
        }
    For some reason all the missing imports cannot be completed. The main exception to this is
    File
    .
    a
    • 2
    • 7
  • z

    zt

    09/13/2022, 2:42 AM
    Is there a simpler way to do this
    val vendor = buildString {
        repeat(lengthOfVendor) {
            append(readChannel.readByte().toInt().toChar())
        }
    }
    e
    a
    • 3
    • 7
  • s

    Satyam Agarwal

    09/13/2022, 9:46 AM
    Hei ! I see Ktor is very relaxed on using GlobalScope in the framework. However, GlobalScope is marked as delicate api, and I have been bitten by it by abusing it unintentionally. Biggest disadvantage of using GlobalScope is, that it is not bound to any scope, thus it cannot be cancelled, in regards to structured concurrency (correct me if I am wrong). This can easily lead to memory leaks and unclosed operations. Have the team thought about moving away from GlobalScope ?
    a
    r
    • 3
    • 5
  • j

    Jorge Bo

    09/13/2022, 7:41 PM
    Hi guys, i have question regarding a HttpClient query which is returning a TooLongLineException. Is there any way to fix this issue in ktor? It seems there is a but raised for it https://youtrack.jetbrains.com/issue/KTOR-2588/ByteReadChannel-is-unable-to-read-files-with-long-lines
    "i.k.u.i.c.TooLongLineException: Line is longer than limit\n\tat i.k.u.i.ByteBufferChannel$readUTF8LineToUtf8Suspend$2.invokeSuspend(ByteBufferChannel.kt:2094)\n\tat i.k.u.i.ByteBufferChannel$readUTF8LineToUtf8Suspend$2.invoke(ByteBufferChannel.kt)\n\tat i.k.u.i.ByteBufferChannel$readUTF8LineToUtf8Suspend$2.invoke(ByteBufferChannel.kt)\n\tat i.k.u.i.ByteBufferChannel.lookAheadSuspend$suspendImpl(ByteBufferChannel.kt:1826)\n\tat i.k.u.i.ByteBufferChannel.lookAheadSuspend(ByteBufferChannel.kt)\n\tat i.k.u.i.ByteBufferChannel.readUTF8LineToUtf8Suspend(ByteBufferChannel.kt:2076)\n\tat i.k.u.i.ByteBufferChannel.readUTF8LineToAscii(ByteBufferChannel.kt:2011)\n\tat i.k.u.i.ByteBufferChannel.readUTF8LineTo$suspendImpl(ByteBufferChannel.kt:2113)\n\tat i.k.u.i.ByteBufferChannel.readUTF8LineTo(ByteBufferChannel.kt)\n\tat i.k.u.i.ByteBufferChannel.readUTF8Line$suspendImpl(ByteBufferChannel.kt:2117)\n\tat i.k.u.i.ByteBufferChannel.readUTF8Line(ByteBufferChannel.kt)\n\t
    • 1
    • 1
  • e

    Emil Kantis

    09/14/2022, 10:05 AM
    Using ktor-network, how can I accept incoming connections while still respecting cancellation? acceptSuspend does a
    while (true)
    loop until a connection appears.
    • 1
    • 1
  • p

    PHondogo

    09/14/2022, 11:00 AM
    Hello! How can i make HttpClient's coroutine scope not cancelling on call fails?
    t
    • 2
    • 2
  • t

    Trevor Stone

    09/15/2022, 2:21 AM
    I've been trying to use ktor's auto-reload with embeddedServer, and it seems like everything should be working.
    INFO  ktor.application - Application auto-reloaded in 0.008 seconds.
    the above prints and everything in the console, but the actually responses aren't changing. I'm using coretto 17
    b
    • 2
    • 7
  • m

    martmists

    09/15/2022, 2:18 PM
    In "Sign and encrypt session data" (https://ktor.io/docs/sessions.html#sign_encrypt_session) the example code uses hex strings, can these be of any random hex sequence (assuming they're the same every time), or is there some importance to their values?
    e
    • 2
    • 4
  • j

    joney

    09/16/2022, 9:33 AM
    Hey! Regarding client
    ContentNegotiation
    plugin: I need access to the serialised body (as
    TextContent
    ) in order to calculate a header value: The api I’m using expects a signature header which needs the body content for calculating the signature value 🙃. Snipped of what I’m trying to do in
    HttpRequestPipeline.Send
    phase:
    private val HttpRequestBuilder.bodyAsText get() = (body as? TextContent)?.text
    (Prior to send the body is not available as text) Problem: I cannot set headers anymore after the body had been serialised, is that correct? Do you know a workaround?
    a
    • 2
    • 3
  • a

    Alberto Quario

    09/16/2022, 3:37 PM
    Hi, we are using ktor-client-apache to fetch some json:
    client.request(url) {
        HttpMethod.Get
        accept(ContentType.Application.Json)
        contentType(ContentType.Application.Json)
        timeout { requestTimeoutMillis = 60 * 1000
                  connectTimeoutMillis = 5 * 1000
                  socketTimeoutMillis = 60 * 1000 }
    }
    Using ktor 2.0.3 we never had any problems, with version 2.1.0 and 2.1.1 sometimes the call fails with:
    org.apache.http.ConnectionClosedException: Premature end of Content-Length delimited message body (expected: 41,606; received: 26,090)
    Same code with the old ktor version started to work again correctly. Anyone having the same problem? Any hint on how to fix it? Thanks!
    a
    • 2
    • 2
  • m

    mytrile

    09/17/2022, 7:07 AM
    Hi, is there a lib for authentication/authorization with baked in storage for session in DB or I should implement it by my self using sessions plug ? Something like https://github.com/heartcombo/devise
    a
    • 2
    • 1
  • a

    Ayfri

    09/17/2022, 12:29 PM
    Hi, while trying to deserialize an array of data, I got an error when trying to deserialize an empty JSON array that was sent with
    prettyPrint
    , so
    [
    
    ]
    I get an error
    io.ktor.serialization.JsonConvertException: Illegal input
    , which doesn't occur when using only
    kotlinx.serialization
    a
    • 2
    • 2
  • n

    Norbi

    09/18/2022, 6:14 PM
    What value should I pass to `BearerTokens`' constructor as the (non-nullable)
    refreshToken
    property if there is no refresh token (in case of _client_credentials_ flow)? Thanks.
    a
    • 2
    • 1
  • z

    zt

    09/19/2022, 2:42 AM
    I'm trying to make a multiplatform library that wraps some API functions with ktor and I've run into the issue of how to design the libraries client constructor. Should the user just be able to call it with no args and have the library create the HttpClient, or some other design? This is the first time I've tried making a library so im a little unfamiliar right now
    n
    a
    a
    • 4
    • 7
  • h

    hhariri

    09/19/2022, 10:32 AM
    📣 Please take a few minutes to fill out our survey. It helps us tremendously. Thank you https://surveys.jetbrains.com/s3/ktor-annual-customer-survey-2022 📣
    • 1
    • 1
  • p

    Partho Paul

    09/19/2022, 3:11 PM
    Hello Folks, I’m trying to start a ktor server which is dependent upon my application.conf file. I’m using embeddedServer with custom shutdown hook as below:
    fun main(args: Array<String>): Unit = runBlocking(Dispatchers.Default) {
        embeddedServer(
            Netty,
        ) { module() }.awaitShutdown()
    }
    
    fun Application.module(testing: Boolean = false) {
        configureMonitoring()
        configureRouting()
        configureSerialization()
        configureHTTP()
        configureKoin()
        statusPage()
    }
    But I’m not sure where to pass the args from conf file. I know I can use
    fun main(args: Array<String>): Unit = EngineMain.main(args)
    instead of embeddedServer but I’m not sure I can add custom shutdown hook to it. Can someone please help me for this?
    a
    • 2
    • 5
Powered by Linen
Title
p

Partho Paul

09/19/2022, 3:11 PM
Hello Folks, I’m trying to start a ktor server which is dependent upon my application.conf file. I’m using embeddedServer with custom shutdown hook as below:
fun main(args: Array<String>): Unit = runBlocking(Dispatchers.Default) {
    embeddedServer(
        Netty,
    ) { module() }.awaitShutdown()
}

fun Application.module(testing: Boolean = false) {
    configureMonitoring()
    configureRouting()
    configureSerialization()
    configureHTTP()
    configureKoin()
    statusPage()
}
But I’m not sure where to pass the args from conf file. I know I can use
fun main(args: Array<String>): Unit = EngineMain.main(args)
instead of embeddedServer but I’m not sure I can add custom shutdown hook to it. Can someone please help me for this?
a

August Lilleaas

09/19/2022, 5:46 PM
how are you reading the config file, and where do you need to pass it to?
p

Partho Paul

09/20/2022, 4:51 AM
@August Lilleaas While using
EngineMain.main(args)
implementation, I’m able to read the config via
environment.config.property(key).getString()
. Using the same for embeddedServer is not working and is throwing
io.ktor.server.config.ApplicationConfigurationException: Property ktor.api.customkey not found
a

August Lilleaas

09/20/2022, 6:40 AM
ah, right. That makes sense, I believe the difference between embeddedServer and EngineMain.main(..) is that with embeddedServer, you configure Ktor programmatically instead of by config file?
you could use a library such as Typesafe Config to read a .conf file instead
p

Partho Paul

09/20/2022, 9:29 AM
@August Lilleaas Thanks for the hint. Was able to implement it as:
val environment = applicationEngineEnvironment {
      this.parentCoroutineContext = coroutineContext + parentCoroutineContext
      this.log = KtorSimpleLogger("ktor.application")
      this.connectors.addAll(connectors)
      this.config = HoconApplicationConfig(ConfigFactory.load())
    }

    embeddedServer(factory, environment, configure).apply { start() }
View count: 18