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

    xxfast

    02/04/2022, 2:20 AM
    is there an official openapi-generator for kotlin ktor client?
    ✅ 1
    a
    r
    m
    • 4
    • 6
  • с

    Стефан Јовановић

    02/04/2022, 8:15 AM
    I was wondering if there's a way to properly TEST authentication with Ktor? Authentication with Session cookies to be exact?
    authenticate("auth-session") {}
    a
    • 2
    • 1
  • j

    Joris PZ

    02/04/2022, 9:00 AM
    I'm updating an plugin for authorization I made for Ktor 1.6 to the new 2.0.0 Plugin concept, but I am running into an issue I don't understand. Say I want plugin
    Foo
    to run after the existing
    Authentication
    plugin. When I try
    val Foo = createApplicationPlugin("Foo") {
        after(Authentication) {
    
        }
    }
    the line starting with
    after
    generates a compiler error:
    Type mismatch.
    Required: io.ktor.server.application.Plugin<*, *, PluginInstance>
    Found: io.ktor.server.auth.Authentication.Plugin
    The supertype of
    io.ktor.server.auth.Authentication.Plugin
    is
    ApplicationPlugin<Application, Configuration, Authentication>
    . Now I am not strong on generics, but I guess this is indeed not a subtype of the required
    io.ktor.server.application.Plugin<*, *, PluginInstance>
    (Is this the same issue as you talk about here, @hhariri?) Is there any way to make my plugin run after the Authentication plugin?
    a
    r
    • 3
    • 5
  • m

    Mitchel Nijdam

    02/04/2022, 11:56 AM
    This week I promoted Ktor in the largest Dutch Java Magazine (4 pages in total) 😁 https://twitter.com/MitchelNijdam
    👍🏼 1
    🇳🇱 4
    👍 4
    :kotlin-intensifies-purple: 9
    🔥 21
    e
    e
    s
    • 4
    • 6
  • l

    Lukasz Kalnik

    02/04/2022, 11:58 PM
    I migrated to 2.0 but attaching query parameters with api key in
    defaultRequest
    seems not to work anymore:
    HttpClient {
                // ... 
                defaultRequest {
                    url {
                        protocol = URLProtocol.HTTPS
                        host = "<http://api.themoviedb.org|api.themoviedb.org>"
                        encodedPath = "/3$encodedPath" // prepend API version to path
                        parametersOf("api_key", "my_api_key_value")
                    }
                }
             }
    
        suspend fun getConfiguration(): ApiConfig = client.get("configuration").body()
    produces:
    io.ktor.client.plugins.ClientRequestException: Client request(GET <https://api.themoviedb.org/3/configuration>) invalid: 401 Unauthorized. Text: "{"status_code":7,"status_message":"Invalid API key: You must be granted a valid key.","success":false}
    a
    • 2
    • 2
  • s

    SooYoung

    02/05/2022, 2:10 AM
    Hello, I’m trying to set “Content-Type” header to just “application/json”, but Ktor client automatically send request with the header set to “application/json; *charset=UTF-8*”. How can I remove the charset parameter from the header? I’m using ktor
    2.0.0-beta-1
    .
    a
    • 2
    • 2
  • j

    jw

    02/05/2022, 4:02 AM
    Why does ktor use typesafe config instead of kotlinx.serialization HOCON support? Typesafe config drags in java.desktop module and it's the only reference to that module in my project.
    r
    • 2
    • 2
  • j

    jw

    02/05/2022, 4:10 AM
    A separate but related question, should Ktor's HOCON configuration support be its own artifact that is not part of the core? I'm sure people use it, but I also suspect most do not.
    👍 3
    r
    • 2
    • 4
  • l

    Landry Norris

    02/05/2022, 8:07 PM
    I'm using the Koin Ktor extension in one of my server projects. When I updated to the 2.0.0 beta, I'm getting errors because it looks like the Koin feature hasn't been updated to the new plugins architecture. Is there a way around this for now, perhaps a way to install a plugin made for Ktor 1.6.x?
    a
    • 2
    • 2
  • a

    andylamax

    02/06/2022, 11:28 AM
    Just finished migrating our large project to ktor 2 The only hustle I got was realizing that CORS doesn't come bundled as in Ktor 1, it comes in a separate artifact
    io.ktor:server-cors
    Apart from that, I haven't come across any hardships really in the whole migration process, process took approximate 20 minutes. Taking into account that this was a multiplatform project with ktor both on the server and client side. Anyone who was skeptical migrating to it, should not be worried at all
    :tnx: 1
    🎉 1
    👍 2
    🤘 5
    e
    v
    • 3
    • 3
  • o

    Ovsyannikov Alexey

    02/07/2022, 3:31 PM
    Hello 🙂 is there any way to upload multipart forms with large files from js? As I understand, by default in JS is used
    window.fetch
    , but I didn't found any way in ktor to upload files as streams
    a
    • 2
    • 4
  • j

    Johnny Baloney

    02/07/2022, 4:22 PM
    Hello, I was browsing Ktor related resources and came across Ktor 1.3 release notes. There I found this snippet:
    Ktor now supports a way to construct a JSON body using the
    kotlinx.serialization
    DSL:
    <http://client.post|client.post>("<http://localhost:9090>") {
    contentType(ContentType.Application.Json)
    body = json {
    "key1" to 123
    "map" to json {
    "key2" to "abc"
    }
    }
    }
    To use it on a client, install JsonFeature and add the ktor-client-serialization dependency.
    When I paste this into the editor
    json
    function is not recognised. How do I enable the kotlinx.serialization DSL?
    a
    a
    • 3
    • 3
  • c

    cafonsomota

    02/08/2022, 3:42 PM
    hello all! is there any release date for 2.0.0 final? 🙂
    e
    h
    • 3
    • 3
  • d

    dimsuz

    02/08/2022, 4:25 PM
    When using ktor with kotlin
    1.6.10
    and kotlin-native (iOS), whenever default
    logger
    is installed on HttpClient, it fails some responses with
    Fail to create response observer in different native thread.
    Is there a workaround for this? Removing http
    logger
    fixes this, seems like some internal ktor bug.
    • 1
    • 1
  • c

    calrissian

    02/08/2022, 11:56 PM
    I have some static content (javascript) that I would like to be able to call different host based on the environment (local, dev, prod) that the ktor server is running in.. ideas of if there is a way to accomplish this?
    b
    • 2
    • 4
  • b

    ByteZ

    02/09/2022, 3:23 PM
    Does ktor automatically convert request header keys to some weird camel case? My GitHub webhook allegedly sends the header
    X-GitHub-Event
    but the server receives
    X-Github-Event
    with a lower case h. I've contacted GitHub support and they said it's caused by the receiving server. If it Is caused by ktor, is there a way to keep the original names?
    s
    a
    • 3
    • 4
  • l

    Lucas

    02/10/2022, 5:12 PM
    Trying to set Ktor's client body as Array<MyClass> gives me java.lang.ClassCastException: [LMyClass; cannot be cast to MyClass If i just set body as MyClass it works fine Not sure what i'm doing wrong
    t
    a
    • 3
    • 3
  • j

    Javier

    02/10/2022, 10:04 PM
    If I want to catch an exception (
    java.nio.channels.UnresolvedAddressException
    ) in my custom plugin, in which phase should I do that?
    a
    • 2
    • 1
  • t

    Tunji Dahunsi

    02/10/2022, 11:05 PM
    I’m trying to setup a middleware like chain for processing ktor client errors. Imagine a pipeline of
    [ModelValidationHandler, AuthErrorHandler]
    and so on. Similar to the
    Logging
    feature, I’ve implemented my handlers as
    HttpClientFeature<*, *>
    . The issue I’m having is once one of my handlers reads the
    content
    ByteReadChannel
    of the
    HttpResponse
    as a
    String
    , the channel is fully read, and no other Handler can read it. I read the response like this:
    val observer: ResponseHandler = { response ->
                    try {
                        val message = response.content
                                .readRemaining()
                                .readText(charset = response.charset()?: Charsets.UTF_8)
                    } catch (_: Throwable) {
                    } 
                }
    
                ResponseObserver.install(ResponseObserver(observer), scope)
    The
    Logging
    feature does not have this limitation. It can log the response, and I can still read it once. Am I consuming the wrong response?
    • 1
    • 1
  • l

    Leonid Golberg

    02/11/2022, 9:34 AM
    Hi All! Has anyone see this error:
    Coroutines must be initialized from the main thread: call 'initMainThread' from the main thread first
    ?
    I am launching raw socket API on iOS, ktor version
    2.0.0-beta-1
    e
    t
    • 3
    • 8
  • p

    Piotr Prus

    02/11/2022, 5:04 PM
    Hi everyone 👋 I would like to build a feature to dynamically change the DEV and PROD baseUrl parameter for ktor. Client side(KMM). I found some threads for OkHttp, but nothing for Ktor. Any advice how to build such feature?
    d
    • 2
    • 1
  • m

    michaelv

    02/12/2022, 1:02 AM
    Following the documentation I currently have
    install(StatusPages) {
    exception<Throwable> { cause ->
    call.respond(HttpStatusCode.InternalServerError)
    }
    }
    But if I use 2.0.0-beta-1 instead of 2.0.0-eap-256 then it complains like this. Anyone else seeing that? I did a search and didn’t see anyone post about it yet. https://ktor.io/docs/status-pages.html#exceptions
    • 1
    • 1
  • j

    Júlio Santos

    02/12/2022, 2:41 AM
    What's up guys? Do you happen to have a repository of a Rest API made with Ktor JS?
    b
    a
    • 3
    • 3
  • l

    LastExceed

    02/12/2022, 7:31 AM
    how do i stop a tcp ServerSocket from occupyuing a port? i tried
    .close
    .awaitClose()
    and
    .dispose()
    but as long as the program is running it's not letting any other programs listen on that port
    a
    • 2
    • 1
  • s

    Stephan Schroeder

    02/12/2022, 8:54 PM
    UPDATE: I got it running! I started from the ktor-serialisation example here https://github.com/ktorio/ktor-documentation/tree/main/codeSnippets/snippets/json-kotlinx and introduced my code. I'm not sure what I missed in the first place, but now it runs. So I'm trying out ktor and something in my setup must be wrong:
    fun main() {
        embeddedServer(Netty, port = 8080, host = "localhost") {
            configureRouting()
            configureSerialization()
        }.start(wait = true)
    }
    
    fun Application.configureSerialization() {
        install(ContentNegotiation) {
            json(Json {
                prettyPrint = true
                isLenient = true
            })
        }
    }
    fun Application.configureRouting() {
        routing {
            get("/") {
                call.respondText("Wolt Opening Times Formatter")
            }
            post("/") {
                val data = call.receive<String>()
                call.respondText(data.toString())
            }
        }
    }
    so the GET works and POSTing a String works as well, but as soon as I try to parse into something more ambicious, this fails, e.g. let's update the POST like this
    post("/") {
                val data = call.receive<TestData>()
                call.respondText(data.toString())
            }
        }
    }
    @kotlinx.serialization.Serializable
    data class TestData(
        val monday: Int,
    )
    then sending over this json
    {
      "monday": 12
    }
    fails with
    Cannot transform this request's content to simonvoid.gmx.de.time_formatter.plugins.TestData
    io.ktor.features.CannotTransformContentToTypeException: Cannot transform this request's content to simonvoid.gmx.de.time_formatter.plugins.TestData`
    ...
    Caused by: io.ktor.features.CannotTransformContentToTypeException: Cannot transform this request's content to simonvoid.gmx.de.time_formatter.plugins.TestData
    it's the same exception when I try to receive into a Map (
    val data = call.receive<Map<String,Int>>()
    ).
    Caused by: io.ktor.features.CannotTransformContentToTypeException: Cannot transform this request's content to kotlin.collections.Map<kotlin.String, kotlin.Int>
    a
    • 2
    • 2
  • a

    alightgoesout

    02/14/2022, 1:11 PM
    Is there a way to be notified when the Ktor application has started and is ready to accept connections?
    a
    • 2
    • 2
  • l

    Landry Norris

    02/14/2022, 10:30 PM
    I need to connect to a device directly to get data from a REST API it hosts. I’m using ktor client for this. When I am only connected to the device via wifi, I can use a base url of 10.0.0.1 and everything works fine, but when I turn on LTE, ktor gets a 404 on all the calls. I think this is because the device doesn’t provide internet, so ktor favors LTE, which does. Is there a way to configure a ktor client to ignore LTE and only communicate via wifi?
    a
    • 2
    • 2
  • l

    Lucas León

    02/15/2022, 5:23 AM
    Hi everyone! I’ve created a test project with Spring Boot + Ktor Client and wanted to know how to mock Ktor Client responses. This is my setup:
    @SpringBootApplication
    class TodoConsumerApplication {
        @Bean
        fun httpClient() = HttpClient {
            install(JsonFeature)
        }
    }
    
    fun main(args: Array<String>) {
        runApplication<TodoConsumerApplication>(*args)
    }
    @Service
    class TodoConsumerService(
        private val httpClient: HttpClient
    ) {
        suspend fun getItemsTwoTimes() {
            val result1 = httpClient.get<String>("<http://localhost:8080/items>")
            val result2 = httpClient.get<String>("<http://localhost:8080/items>")
    
            println("Result 1 = $result1 and Result 2 = $result2")
        }
    }
    @ExtendWith(SpringExtension::class)
    @SpringBootTest
    internal class TodoConsumerServiceTest {
        @MockkBean
        private lateinit var httpClient: HttpClient
    
        @Autowired
        private lateinit var todoConsumerService: TodoConsumerService
    
        @Test
        fun getItemsTwoTimes() = runBlocking {
    
        }
    }
    I want to mock two different responses in the service using MockEngine
    a
    m
    • 3
    • 5
  • k

    Kedar

    02/15/2022, 1:59 PM
    I've created an application that connects to MongoDb atlas cluster and is hosted on heroku. My question is, when the api server application is idle for long time, and the next client request comes in, does the server application start from its defined main entry point (in my case it's `Application.module`())?
    a
    a
    • 3
    • 2
  • k

    Karl Azzam

    02/15/2022, 10:15 PM
    In terms of negatives, I think the community being small compared to spring means a lot of gotchas can take longer to debug, some of the documentation is outdated (i.e httpresponse has been deprecated for httpstatement and is still the go to example for http clients), and finally imo supporting multiplatform worries me, is it going to become a master of none jack of all trades type ordeal or will they focus mainly on being a kickass framework for server and clients
    b
    l
    • 3
    • 16
Powered by Linen
Title
k

Karl Azzam

02/15/2022, 10:15 PM
In terms of negatives, I think the community being small compared to spring means a lot of gotchas can take longer to debug, some of the documentation is outdated (i.e httpresponse has been deprecated for httpstatement and is still the go to example for http clients), and finally imo supporting multiplatform worries me, is it going to become a master of none jack of all trades type ordeal or will they focus mainly on being a kickass framework for server and clients
b

Big Chungus

02/15/2022, 10:17 PM
Totally valid point. However, to be a devil's advocate, I would say that since ktor is mostly reflectionless (a.k.a. no "black magic") means that unexpected issues happen way less frequently.
k

Karl Azzam

02/15/2022, 10:21 PM
Yeah that no black magic is great in that once u get used to ktor, debugging is pretty chillax
Curious if youre using a HOCON file or init ur config inside the code @Big Chungus . I like how readable HOCON files are although i wish there was 1. A way to inject variables via Hashicorp vault, AWS secret manager, etc in the HOCON file. I was trying to find a way to run code before the HOCON file gets read so u can invoke the api for these secret managers and read them in
And 2. A way to differentiate the env (dev, prod, etc) via multiple HOCON files and their name i.e application-dev.hocon. Spring has this via profiles
l

Landry Norris

02/15/2022, 10:37 PM
For setting up variables, I generally set up a CI pipeline for deployment, and I have a script that uses sed to replace variables right before uploading.
For multiple Hocon files: I’ve set this up before, but you have to give up the nicety of EngineMain and set up the startup code yourself.
k

Karl Azzam

02/15/2022, 10:45 PM
@Landry Norris how do u handle updating variables without having to rekickoff your CI pipeline
Storing config and secrets in vault, k8 secrets, aws secret manager, etc means u can update a secret, bounce the service, and then it will use the latest version
Lets say i use vault. I would prefer a way to hit the vault api and retrieve all the secrets before the server is initialized
l

Landry Norris

02/15/2022, 10:52 PM
That is the main downside. I have to restart my CI pipeline whenever I need the variables changed. I have that set up as part of how I handle changes in variables, but that may just be me.
I’ve never used Vault. You may be able to use Ktor Client to retrieve keys in the module function or in the main function if Vault has a REST API.
k

Karl Azzam

02/15/2022, 10:55 PM
Yeah thats what im doing now (Vault has a REST api) however im looking for a way to hit it and then override what ever is being used to substitute variables in the hocon file
l

Landry Norris

02/15/2022, 10:56 PM
I see. I don’t know of any way to do that.
Are these configuration variables all custom or do you also want to change vars that Ktor recognizes? If it’s all custom, you could wrap that in as part of the abstraction.
k

Karl Azzam

02/15/2022, 11:00 PM
Theres prob a way i gotta read into the ktor code, theyre doing the same concept by allowing u to substitute the application modules as variables in hocon instead of code
All custom yeah, other frameworks like dropwizard and spring allow u to override the variable substitute class with ur own impl (i.e dropwizard: https://github.com/dropwizard/dropwizard/blob/master/dropwizard-configuration/src/main/java/io/dropwizard/configuration/SubstitutingSourceProvider.java)
View count: 7