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

    Derek Seroky

    02/01/2019, 4:11 PM
    @Jonas Bark absolutely, I was just hoping to get general feedback here before doing so to make sure I hadn't missed anything obvious when going through the docs.
    j
    • 2
    • 2
  • n

    ninrod

    02/01/2019, 11:51 PM
    should the best course of action in this scenario to use java libraries like this: https://bitbucket.org/b_c/jose4j/wiki/Home or this: https://github.com/jwtk/jjwt?
    a
    • 2
    • 2
  • s

    Szymon Tosik

    02/03/2019, 3:28 PM
    Any chance someone could look at the issue I created two days ago? https://github.com/ktorio/ktor/issues/917, maybe someone knows how could I consume Flowable to return its result as a json to the client
    v
    • 2
    • 2
  • j

    JoakimForslund

    02/05/2019, 9:35 AM
    Why is the httpClient.request changing response/return type depending on if i use Features or not? Trying to wrap a promise like solution to the httpClient.request response but for whatever reason it will change between HttpResponse and io.ktor.client.features.observer.DelegatedResponse if I use logging. This is while using KotlinxSerializer too, so it does not even seem to map it to json
    • 1
    • 3
  • d

    Davide Giuseppe Farella

    02/05/2019, 10:20 AM
    Just got this error during the build, of an Android multi-module project:
    More than one file was found with OS independent path 'META-INF/ktor-http.kotlin_module'
    j
    • 2
    • 4
  • g

    galex

    02/06/2019, 9:38 AM
    HttpClient shows up in red in IntelliJ even when there is no errors (compile works, alt+click works on it as well), is that a known bug?
    e
    r
    • 3
    • 3
  • k

    Kenneth

    02/06/2019, 9:52 PM
    I am trying to add cookies and now get
    java.lang.IllegalArgumentException: Couldn't instantiate type class Session for parameters [value]
    whenever I call an endpoint.
    • 1
    • 2
  • n

    nestserau

    02/07/2019, 2:11 PM
    I have the following code, which is a part of a MPP library which I now use from iOS. The problem is that sometimes the size of
    input
    gets less than intended, in other words I don’t get the data in its entirety. Via Wireshark I’ve verified that the problem is not on the backend side, I always receive the same amount of bytes via the network interface and the bytes are also the same. But in 1-10% of cases
    input
    is shorter than intended.
    private val client = HttpClient()
    
    suspend fun <T> send(...): ... {
    
            val response: HttpResponse
    
            try {
                response = <http://client.post|client.post>(url) { body = payload }
            } catch (e: Throwable) {
                ...
            }
    
            if (response.status != HttpStatusCode.OK) {
                return ...
            }
    
            val input = response.readBytes().asUByteArray()
            ...
    }
    Thoughts?
    e
    c
    • 3
    • 4
  • n

    napperley

    02/08/2019, 12:33 AM
    Is there any way to get a more helpful error message from the Ktor Client (using Gson as the JSON serializer)? End up with this confusing error: Fail to run receive pipeline 😕
    • 1
    • 4
  • r

    Riccardo Montagnin

    02/08/2019, 10:53 AM
    Hello everyone, I have a problem while using Jackson ContentNegotiation inside Ktor. I keep getting
    InvalidDefinitionException - (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
    I'm installing the feature as follows:
    install(ContentNegotiation) {
                jackson {
    
                    // Set how the dates should be handled
                    dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").apply {
                        timeZone = TimeZone.getTimeZone("UTC")
                    }
    
                    // Do not serialize null values
                    setSerializationInclusion(JsonInclude.Include.NON_NULL)
    
                    // Do not worry about unknown properties, ignoring them
                    configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
    
                    // If we receive an empty object, treat it as null
                    enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT)
    
                    //accept also lowercase value in enum fields
                    enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS)
                }
            }
    Every time I do something like
    call.receive<MyClass>()
    I get that error. How could I resolve the issue?
    m
    • 2
    • 13
  • c

    Charlie

    02/08/2019, 4:58 PM
    hey guys, I'm just starting to learn Kotlin for a new job I start in a couple weeks. Would you recommend learning ktor along with it, or should I focus on the language fundamentals first and start with integrating something like Spring Boot, Micronaut, or some other solution for building REST APIs?
    r
    h
    a
    • 4
    • 7
  • a

    Alan Pierri

    02/08/2019, 6:21 PM
    Hi everyone! Maybe someone encountered the same challenge...
    lateinit var foo: Foo
    
    fun Application.main() {
      if(!::foo.isInitialized){
        // Initialize foo, which is heavy processing...
      }
      // More code...
    }
    Is there any way I can avoid re-initializing foo with Autoreload? I hoped the initialization check would work, but it won't.
    r
    b
    • 3
    • 2
  • n

    napperley

    02/08/2019, 10:27 PM
    Is there a Android example that uses the Ktor HTTP client for JSON serialization/deserialization with a REST API?
    s
    • 2
    • 1
  • f

    frellan

    02/09/2019, 4:25 PM
    Why does the route not return until what is running inside the launch is done? I thought that
    launch
    returned immediatly and ran whatever was inside on a new thread.
    launch {
        doStuff()
    }
    call.respond(Created)
    b
    a
    • 3
    • 5
  • f

    frellan

    02/09/2019, 9:56 PM
    How do one conditionally apply authentication in ktor? 😛 I want to skip it in development since I do not send
    basic
    auth headers then
    z
    a
    • 3
    • 3
  • i

    Ian

    02/10/2019, 4:05 PM
    For routing, why did Ktor go with
    "/mouse/{id}"
    rather than
    "/mouse/:id"
    , which seems a little more common?
    o
    • 2
    • 3
  • m

    Manuel Lorenzo

    02/11/2019, 2:50 PM
    oh great another one then? 🙂
    d
    z
    m
    • 4
    • 6
  • m

    mp

    02/11/2019, 9:30 PM
    Yep, when you post something to the test application engine, you now need to specify the content type
    t
    m
    • 3
    • 8
  • o

    obobo

    02/11/2019, 9:56 PM
    I'm using the Ktor CIO client to call an external service. If the service takes over a certain threshold to respond I want it to fail. Is there any way to do this in the client? I'm currently wrapping the client call with
    withTimeout
    , but will this handle cleanup properly, will it cancel the in-flight request? (I'm aware of, and using,
    connectTimeout
    , but I want to timeout on the request as a whole, not just opening a connection.)
    e
    • 2
    • 1
  • k

    kevin

    02/12/2019, 7:31 AM
    Is there a way in Ktor to have multiple routes go to the same handler. For example I’d like “/api/todos” and /api/v1/todos” to be the same branch of the tree?
    s
    • 2
    • 3
  • m

    Manuel Lorenzo

    02/12/2019, 10:28 AM
    I know there’s https://ktor.io/servers/uploads, but I just don’t know where to upload them and keep a reference in my DB
    g
    • 2
    • 2
  • d

    Damiano Giusti

    02/12/2019, 1:47 PM
    Hi, anyone has problems with the Ktor Http Client for Kotlin/Native? When instantiating a
    HttpClient
    compiled against iOS it crashes because the
    Charset.ISO_8859_1
    is not found. Kotlin 1.3.21, Ktor Client 1.1.2
    e
    • 2
    • 6
  • d

    Damiano Giusti

    02/12/2019, 2:18 PM
    Probably the IAE at 61 here https://github.com/Kotlin/kotlinx-io/blob/master/native/src/kotlinx/io/charsets/CharsetNative.kt#L61
    • 1
    • 1
  • h

    hmole

    02/12/2019, 6:25 PM
    Can I somehow accept body in
    DELETE
    route method? Right now it returns 415.
    • 1
    • 1
  • d

    Dias

    02/13/2019, 11:27 AM
    When I use ktor http client I want to read a message that comes with an unsuccessful response status, like 500, but when I call
    response.receive<String>()
    it throws with BadResponseStatusException. I kinda understand the reason for that, but how do I read a message that comes with bad response?
    e
    • 2
    • 2
  • a

    Andy

    02/13/2019, 3:15 PM
    Does putting a runBlocking in a ktor route block the web server from receiving more requests?
    runBlocking {
                delay(500)
        }
    b
    • 2
    • 1
  • g

    galex

    02/13/2019, 8:29 PM
    How do I write a file upload request + json body in Ktor client common (mpp) ?
    • 1
    • 1
  • g

    galex

    02/14/2019, 6:02 AM
    When uploading an base64 encoded image with ktor-core (common sourceset) when the image is bigger than around 200k I get the following error:
    IllegalArgumentException {message_8yp7un$_0: "should should be greater than write space + end ga… = 9, writeRemaining = 0, endGap = 8, rem+gap = 8", cause_th0jdv$_0: null, name: "IllegalArgumentException", stack: "IllegalArgumentException: should should be greater…8td$_0 (<http://localhost:9000/bundle.js:31435:19>)"}
    👀 1
    r
    • 2
    • 12
  • b

    bod

    02/14/2019, 11:20 AM
    Hello, World! I have a pattern that happens a lot in our codebase: enums with a String key, and we need to get the enum value from the key, or a special “unknown” value. So what we do currently is something like:
    enum class MyEnum(val key: String) {
        FOO("foo"),
        BAR("bar"),
        UNKNOWN("unknown");
    
        companion object {
            fun getByKey(key: String?): MyEnum {
                return MyEnum.values().firstOrNull { it.key == key } ?: MyEnum.UNKNOWN
            }
        }
    }
    I’m looking for a way to not repeat this companion object for all our enums. Possibly a combination of an interface and a generic extension function? Any idea? 🙂
    d
    m
    • 3
    • 24
  • i

    igorvd

    02/14/2019, 5:12 PM
    how do I define the routings on another module? I try to add this to the
    application.conf
    modules = [ com.example.ApplicationKt.module, com.example.user.UserModuleKt.module ]
    and create this extension into the UserModule file:
    package com.example.user
    
    fun Application.module() {
        routing {
            route("/users") {
                get {
                    call.respondText("Users", ContentType.Text.Plain)
                }
            }
        }
    }
    when I try to conect to the /users endpoint, I'm getting a 404 error 😕
    c
    • 2
    • 8
Powered by Linen
Title
i

igorvd

02/14/2019, 5:12 PM
how do I define the routings on another module? I try to add this to the
application.conf
modules = [ com.example.ApplicationKt.module, com.example.user.UserModuleKt.module ]
and create this extension into the UserModule file:
package com.example.user

fun Application.module() {
    routing {
        route("/users") {
            get {
                call.respondText("Users", ContentType.Text.Plain)
            }
        }
    }
}
when I try to conect to the /users endpoint, I'm getting a 404 error 😕
c

cy

02/14/2019, 5:19 PM
This actually should work. Need to be investigated...
i

igorvd

02/14/2019, 5:26 PM
Do you want a project copy? It's my first time using Ktor, I was basically just reading the documentation and testing stuff, so I'm not sure if I'm doing something wrong
c

cy

02/14/2019, 5:28 PM
Do any routes actually work? Or just routes from extra modules do not work?
i

igorvd

02/14/2019, 5:32 PM
the routes on the
Application.kt
file works, with this content:
fun main(args: Array<String>) {
    val server = embeddedServer(Netty, port = 9000) {

        routing {

            trace { application.log.trace(it.buildText()) }

            get("/") {
                
                call.respondText("Hello World!", ContentType.Text.Plain)

            }

        }
    }
    server.start(wait = true)
}
when I cut the route
/users
from the other file and paste here, works too
c

cy

02/15/2019, 8:45 AM
People usually extract modules to separate functions and simply invoke them from main module functions this is why this bug wasn't discovered yet.
Will fix that, thanks
i

igorvd

02/15/2019, 5:03 PM
Cool. Thanks for your feedback 🙂
View count: 2