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

    johnaqel

    06/30/2021, 12:34 AM
    Hi folks. Let’s say I have a string representing a path “/some/path”. I’d like to know if a route has been defined for that path. Is there a way to search and see if a route matching that path has already been defined?
    c
    a
    • 3
    • 3
  • j

    Júlio Santos

    06/30/2021, 12:58 PM
    Hey guys! What's up? Does anyone here have an example of using Ktor with Apache Kafka?
    h
    • 2
    • 14
  • r

    ribesg

    07/01/2021, 10:21 AM
    What’s your strategy to return meaningful error to the user from a Ktor Server when using Kotlinx Serialization to parse the body of a request, and the body isn’t valid?
    h
    h
    +2
    • 5
    • 10
  • d

    divyanshunegi

    07/02/2021, 5:14 AM
    suspend fun GETRequest(
        baseUrl:String,
        path: String,
        headers: List<Headers>? = null,
        model: , MODEL_CLASS_NAME
        json: Json = Json {
            ignoreUnknownKeys = true
        }
    ) : MODEL_CLASS {
        val builder = HttpRequestBuilder()
        builder.method = HttpMethod.Get
        builder.url {
            takeFrom(baseUrl)
            encodedPath = encodedPath.let { startingPath ->
                path(path)
                return@let startingPath + encodedPath.substring(1)
            }
        }
    
        with(builder.headers) {
            if (!headers.isNullOrEmpty()) {
                headers.forEach {
                    append(it.key, it.value)
                }
            }
        }
    
        try {
            val serializer = model.serializer()
    
            //not primitive type
            val result: String = httpApiClient.request(builder)
            return json.decodeFromString(serializer, result)
        } catch (pipeline: ReceivePipelineException) {
            throw pipeline.cause
        }
    }
    I am trying to make a generic GETrequest function which can be used from Android and iOS in Ktor native with KMM, I am not sure how can we pass the
    MODEL_CLASS_NAME
    , any idea ?
    a
    • 2
    • 8
  • s

    Stylianos Gakis

    07/02/2021, 2:40 PM
    When using the Locations plugin, is there a way to specify the body variables instead of just the query parameters? For example I want to have something like this
    @Location("/login")
    data class PostLogin(val username: String, val password: String)
    But I want the
    username
    and the
    password
    to be part of the body of the post request instead of the Params. Is that something that is possible, or must I do
    call.receive
    like I would when I wasn’t using the Locations plugin?
    n
    d
    • 3
    • 5
  • l

    Lucas Milotich

    07/02/2021, 9:19 PM
    Hello everybody, I would want to know if someone knows what happens with the resources that a client it’s using in a http call if the coroutine is cancelled by any of the previous coroutines . I saw there’s a method in the response class:
    public fun CoroutineScope.cancel(message: String, cause: Throwable? = null): Unit = cancel(CancellationException(message, cause))
    But it just cancel de coroutine and i don’t know what happens with the connection, buffers, etc. Thanks!
    a
    • 2
    • 2
  • h

    Helio

    07/03/2021, 6:54 AM
    Hello all, I noticed that after upgrading to Ktor 1.6.1 I had to replace
    embeddedServer(Netty, 8080, module = Application::module).start()
    with
    developmentMode = false
    to be able to run my application locally. Is that expected? I couldn’t find any information in the change logs.
    val builder = ApplicationEngineEnvironmentBuilder()
        builder.module(Application::module)
        embeddedServer(Netty, builder.build {
            developmentMode = false
            connector {
                port = 8080
            }
        }).start()
    The reason I had to do it, was to avoid the a similar error reported here. https://youtrack.jetbrains.com/issue/KTOR-2306
    a
    • 2
    • 3
  • d

    divyanshunegi

    07/06/2021, 10:21 AM
    Hi All, I am working on a generic ktor client abstraction on my iOS and Android app where I want any client to call our networking library and make request and can send the Model they expect and Error Model they expect from the API.
    APIClient.GETRequest<UserData, Error>("/kmm-test", { success -> 
        Log.i(TAG, "Success: ${it.toString()}")
    }, { error -> 
        Log.e(TAG, "Error: ${it.cause}")
    }, { genericError ->
        Log.e(TAG, "Throwable: ${it.message}")
    })
    it looks something like this. I am handeling the generic error with ktor client engine. but the error from API is still a mystery to me, can someone guide me to a good direction ?
    a
    • 2
    • 2
  • j

    Justin Moy

    07/06/2021, 7:07 PM
    hey, we're upgrading from ktor 1.4 to ktor 1.6 and are encountering an
    IllegalStateException
    when trying to use our ktor client to call a ktor server for our integration tests, anyone able to take a look? This is the error message when
    customPost()
    is called:
    Failed to parse request body: request body length should be specified, chunked transfer encoding should be used or keep-alive should be disabled (connection: close)
    setup:
    val httpClient = HttpClient(CIO) {
        expectSuccess = false
      }
    
    suspend inline fun <reified TRequestData> customPost(
        url: String,
        requestCacheKey: String,
        requestContent: TRequestData,
        headers: Map<String, String>? = null,
        contentType: ContentType = ContentType.Application.Json
      ) {
            <http://httpClient.post|httpClient.post><HttpResponse>(url) {
                var contentAstString = requestCacheManager.getOrCreateRawString(requestCacheKey) { requestContent } // returns a string
                headers?.forEach { headerKey, value ->
                    header(headerKey, value)
                }
                body = TextContent(contentAstString, contentType)
            }
      }
    a
    e
    • 3
    • 7
  • d

    divyanshunegi

    07/07/2021, 5:05 PM
    Hello, I am writing a Plugin in Ktor, the idea of this Plugin is to first check if Internet is available, if not cancel request and throw error, and when we receive response we check if the status is
    401
    in that case retry the call after making a new token.
    scope.requestPipeline.intercept(HttpRequestPipeline.State) {
        println("MyNewPlugin : works the scope ${context.method}")
        context.header(HttpHeaders.UserAgent, feature.agent)
    }
    scope.responsePipeline.intercept(HttpRequestPipeline.State) {
        println("MyNewPlugin : works the scope ${context.response.status}")
    }
    I wrote this in the
    install
    function to test the Plugin for request and response pipeline but it crashes with this error
    Caused by: io.ktor.util.pipeline.InvalidPhaseException: Phase Phase('State') was not registered for this pipeline
    a
    • 2
    • 1
  • b

    Brendan Weinstein

    07/08/2021, 6:19 PM
    Is there anyone successfully using ktor on ios via kotlin multiplatform? I gave up trying 6-12 months ago in favor of my own home-grown (but hacky) solution, but curious if the kinks ever got worked out.
    t
    d
    a
    • 4
    • 9
  • a

    Aleksandr Ivanov

    07/09/2021, 12:50 PM
    I’m trying to use new Bearer based authorisation https://ktor.io/docs/auth.html#bearer. Wondering why we need to have
    refreshToken
    in
    BearerTokens
    . I don’t found an usage inside library. In my case I’m storing and refreshing tokens on application side.
    a
    e
    • 3
    • 14
  • m

    MBegemot

    07/09/2021, 4:38 PM
    java.lang.Exception: 
    Exception -> java.lang.IllegalStateException Expected 8 bytes in the trailer. Actual: 7 $
       at io.ktor.util.EncodersJvmKt$inflate$1.invokeSuspend(EncodersJvm.kt:128)
       at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
       at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
       at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:571)
       at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
       at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:678)
       at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:665)
    I'm finding this error at random times, it happens when building up the body parameters in a POST with json. Unfortunately it only happens time to time but of course is annoying , the request is cancelled before being send to the server. (Since version 1.5.4) .
    a
    • 2
    • 2
  • d

    darkmoon_uk

    07/10/2021, 7:44 AM
    After reading the documentation on Ktor Modules, I'm unclear on what advantage there is (if any) to separating a Ktor Server into different 'modules' vs just breaking down a single module into sub-functions for organisation. In particular; it's not stated whether installing a Plugin is scoped to the current module or global to the Application.
    a
    c
    • 3
    • 3
  • d

    David Dupraz

    07/11/2021, 12:56 PM
    Hello. In a ClientRequestException, how to access to the text only ? For example, in
    Client request(<http://localhost:2077/login>) invalid: 400 Bad Request. Text: "Wrong password"
    printed by
    exception.message
    , is there a way to print only "Wrong password" ?
    d
    • 2
    • 2
  • g

    Gus

    07/12/2021, 2:58 PM
    Hi. I run a Ktor server on Android 5+, and I'm trying to upgrade Ktor from 1.4 to 1.6. Unfortunately, some of the changes in ktor uses
    java.nio.file.FileSystems
    , which breaks on Android 5-8 but works in newer versions. This line in `ApplicationEngineEnvironmentReloading` is the culprit, but I don't think that class should be used in production, right? So how can I disable that behaviour, so that that class won't be loaded? I'm not running the server in development mode, so it shouldn't be trying to reload the server.
    👀 1
    a
    • 2
    • 13
  • j

    Joost Klitsie

    07/12/2021, 8:23 PM
    Hello guys! Is it possible for modules to communicate with one another?
    a
    • 2
    • 6
  • c

    CLOVIS

    07/13/2021, 10:26 AM
    I'd like to create a cookie when the client makes a specific request. If I understand correctly, that means I need to add a
    Set-Cookie
    header in the response. However,
    call.respond
    doesn't take a lambda to configure the request, unlike its client-side equivalent. I found
    call.respondText
    , which has an override with a lambda with an
    OutgoingContent
    receiver, which has a
    headers
    attribute, however it seems to be immutable. How can I add a specific header for a specific request? I don't want that header to be present in other requests.
    a
    d
    • 3
    • 5
  • t

    tylerwilson

    07/13/2021, 7:53 PM
    I have a working KMM module using Ktor client on iOS and Android. Trying to add macOS support. I use the following pattern:
    GlobalScope.launch {
        launch(ApplicationDispatcher) {
           client.get {
           }
        }
    }
    but when testing with a macOS SwiftUI app, I get the following:
    Error: There is no event loop. Use runBlocking { ... } to start one.
    but runBlocking cannot be used in the common code. Any solutions to this? Is the above ‘canonical’ way to make Ktor client calls in common code?
    b
    j
    l
    • 4
    • 7
  • y

    yogurtearl

    07/14/2021, 3:49 AM
    Is there any downside to letting exceptions bubble up to the top of the route in ktor server?
    s
    • 2
    • 1
  • m

    maskipli

    07/14/2021, 11:57 AM
    i'm use ktor version 1.6.1 on KMM, for first time call API to Backend its ok, but for the second time is fail and error.
    failed with exception: kotlinx.coroutines.JobCancellationException: Parent job is Completed; job=JobImpl{Completed}
    a
    t
    • 3
    • 3
  • m

    Marcelus Trojahn

    07/14/2021, 7:27 PM
    Good afternoon... I've been trying to figure this out with no luck: Is there any way to make EngineMain use another file instead of application.conf? I'm trying to create a monolith here with several Ktor servers and a application-server-#.conf for each server.
    👀 1
    a
    • 2
    • 2
  • j

    Joseph Magara

    07/14/2021, 8:51 PM
    Hi All 😒imple_smile: 👋 , I’ve been trying to deploy my ktor server to GCP Cloud Run for the last few days but I keep getting this error when the server is being started up.
    Error: Could not find or load main class io.ktor.server.netty.EngineMain
    Does anyone know how to fix it?
    r
    • 2
    • 4
  • a

    andylamax

    07/15/2021, 6:53 AM
    So, based on a deep analysis and help from @napperley I have discovered that the
    ktor-client-curl
    library on a linuxX64 target fails to located libcurl,
    cannot find -lcurl
    I can add a def file but that would fail in my CI encironment. I am confident that I have installed libcurl while I installed curl but I am open to know if that's not the case So, how does one go about having a configuration that can run locally and on CI?
    r
    • 2
    • 2
  • s

    Slavi

    07/15/2021, 12:22 PM
    Hello. Does ktor-server-kotlinMultiplatform support iOS? I guess only ktor-client supports it
    b
    a
    n
    • 4
    • 11
  • o

    okaymak

    07/15/2021, 2:38 PM
    What is the reasoning behind this? I was just trying out 2.0.0-eap, and now I have to add
    .body()
    after every request. This doesn’t look like an improvement at all.
    👀 1
    h
    • 2
    • 1
  • e

    enleur

    07/17/2021, 3:31 PM
    which method of working with failed states in routes more idiomatic? 1.Similar to call.respondRedirect()
    val id = query["id"] ?: return@post call.respondBadRequest()
    2. Using exceptions and StatusPage
    val id = query["id"]  ?: throw BadRequestException()
    c
    a
    • 3
    • 2
  • s

    saket

    07/18/2021, 4:30 AM
    I’m trying to create an adapter between Okio and Ktor. Could someone be able to check if this piece of code for reading from a
    ByteReadChannel
    looks correct?
    private fun ByteReadChannel.source(): okio.Source {
      val channel = this
      return object : okio.Source {
        override fun read(sink: okio.Buffer, byteCount: Long): Long {
          if (byteCount == 0L) return 0L
    
          return runBlocking {
            if (!channel.isClosedForRead) {
              val bytes = channel.toByteArray(byteCount.toInt())
              sink.write(bytes)
              bytes.size.toLong()
            } else {
              -1. // Source is exhausted.
            }
          }
        }
    
        override fun close() = Unit // Couldn't find any way to close ByteReadChannel.
        override fun timeout() = Timeout.NONE
      }
    }
    👀 2
    r
    t
    • 3
    • 6
  • n

    neworldlt

    07/18/2021, 12:23 PM
    I have a fleet of IoT devices and want some GUI to control them. GUI per device. There is nothing in the wild to meet my requirements. But panels themselves are elementary: show some data, let press some buttons to execute something in a shell. Setup Ktor with a few endpoints + WebSocket is easy. But GUI is another story. MPP + kotlin/js + GUI itself requires tons of time. What lib/frameworks/tools are devs using nowadays? My requirements are pretty low, just get shit done and be very fast. It could look ugly as hell. Love to hear some advice.
    d
    r
    +2
    • 5
    • 8
  • m

    Marc Knaup

    07/18/2021, 5:25 PM
    Hey there 👋 Is there any solution by now to forward certain vert.x requests to Ktor? So that Ktor re-uses vert.x’ HTTP server and handles only certain routes.
    b
    r
    k
    • 4
    • 17
Powered by Linen
Title
m

Marc Knaup

07/18/2021, 5:25 PM
Hey there 👋 Is there any solution by now to forward certain vert.x requests to Ktor? So that Ktor re-uses vert.x’ HTTP server and handles only certain routes.
b

Big Chungus

07/18/2021, 5:43 PM
have ktor routes under different port and proxy vert.x requests to
<http://localhost>:<KTOR_PORT>/<path>
?
m

Marc Knaup

07/18/2021, 5:44 PM
That’s my backup plan in case there’s no good solution 😅 Sounds nasty, esp. with websockets involved.
b

Big Chungus

07/18/2021, 5:44 PM
It IS nasty!
Alternatively you could reuse the same services from both, ktor and vert.x
m

Marc Knaup

07/18/2021, 6:01 PM
I can only use one HTTP port
r

Robert Jaros

07/18/2021, 6:01 PM
Why do you need to use both?
m

Marc Knaup

07/18/2021, 6:01 PM
I have a larger vert.x Java project that is to be migrated to Kotlin + Ktor over time. So migrated code would use Ktor route while old code would use vert.x route.
r

Robert Jaros

07/18/2021, 6:12 PM
What advantages gives Ktor vs Vert.x with Kotlin?
➕ 1
m

Marc Knaup

07/18/2021, 6:34 PM
We’re familiar with it.
k

kenkyee

07/18/2021, 7:23 PM
Why not migrate to Quarkus?
b

Big Chungus

07/18/2021, 7:24 PM
You could just as well ask "why not migrate to micronout". All of them are good in their own way. In the end it boils down to preference and familiarity...
➕ 1
👍 1
m

Marc Knaup

07/18/2021, 7:25 PM
Yup. Back on topic please 😄
r

Robert Jaros

07/18/2021, 7:37 PM
You could check the sources of
micronaut-ktor
module, which embeds Ktor inside Micronaut, reusing Micronaut's native http server. https://github.com/micronaut-projects/micronaut-kotlin/tree/master/ktor/src/main/kotlin/io/micronaut/ktor
Here is the guide of the module: https://micronaut-projects.github.io/micronaut-kotlin/latest/guide/
m

Marc Knaup

07/18/2021, 8:45 PM
That replaces the existing HTTP server with Ktor instead of just adding Ktor as 2nd level
k

kenkyee

07/18/2021, 9:33 PM
Quarkus is vert.x underneath which is why I suggested it...
At any rate, doing a proxy is probably simplest but I'd suggest rewriting the websocket piece...
View count: 3