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

    Julien Salvi

    01/25/2021, 11:57 AM
    I made a sample REST API with Ktor coupled with a Postgres database running on a docker compose 🙂 I tried to showcase several Ktor Feature such as StatusPage, Locations, DataConversion... and other very cool external library like Valiktor, Exposed, HikariCP, Flyway...). I am also using swagger to generate my front models (that can be shared with Android apps). This is a tiny cooking API and you can fork it as you want 🙂 Feedback appreciated 🙂 Enjoy! If you have any questions feel free to ask 🙂 https://github.com/Oleur/swcook-ktor-api
    👍 3
    k
    f
    • 3
    • 2
  • p

    Patrick Doering

    01/25/2021, 6:35 PM
    I have a request with rest assured and want to Transfer it to ktor but no Solution worked. I hope somebody can help me. MultiPartSpecification multiPartSpec = new MultiPartSpecBuilder(zipBytes(„fileinput.xml", bodyXmlAsString.getBytes())) .controlName("file") .fileName("myfile.zip") .mimeType("application/zip") .charset(StandardCharsets.UTF_8) .build(); I don‘t know how to do this with ktor.
    t
    • 2
    • 6
  • j

    jvmusin

    01/26/2021, 12:20 PM
    Hi all! I have a Ktor server with a Netty engine. On requests, I just call
    delay
    for some time (say 20 seconds) and then respond with a string. I thought that when I call
    delay
    , I can serve other requests while previous requests are suspended, but instead, I have to wait until those requests are done and only then I'm able to serve new requests. How can I serve new requests when my previous requests are suspended? I thought it works like that by default, but now I really don't understand.
    m
    j
    • 3
    • 8
  • h

    hellman

    01/27/2021, 11:59 AM
    Hey! Is the only way to get a HttpResponse from a call to set expectSuccess to false?
    r
    • 2
    • 1
  • h

    hellman

    01/27/2021, 4:34 PM
    I guess nobody have built a custom swagger codegen generator that can output a ktor client? 😄
    c
    m
    • 3
    • 4
  • g

    Gus

    01/27/2021, 5:48 PM
    Hey folks. I'm getting a rather unhelpful exception from ktor (with okhttp) on Android:
    java.io.IOException: 
      at sun.nio.ch.IOUtil.makePipe (Native Method)
      at sun.nio.ch.PollSelectorImpl.<init> (PollSelectorImpl.java:57)
      at sun.nio.ch.PollSelectorProvider.openSelector (PollSelectorProvider.java:36)
      at io.ktor.network.selector.ActorSelectorManager$1.invokeSuspend (ActorSelectorManager.kt:41)
      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)
    And to make matters worse, the user who experienced it sent the crash report to Google Play Store anonymously, so I can't contact them to ask for more info. I can't reproduce it either (even though I coincidentally have the same phone). Any thoughts on how to get to the bottom of this? It seems like it's happened 5 times to the same user (we're running a beta right now, so it may be a big issue when we eventually launch). I'm using Ktor via a library. Behind the scenes, that library keeps a WebSocket open and makes some
    POST
    requests when certain events happen. I can see that the library is properly handling `IOException`s in WebSocket and HTTP connections.
    • 1
    • 2
  • j

    John O'Reilly

    01/27/2021, 8:07 PM
    sorry if this is basic question but couldn't find answer in docs.....basicaly in a SPA setup I want any requests that would normally return a 404 to redirect to say main index.html....is there way to configure this in Ktor?
    j
    c
    m
    • 4
    • 5
  • a

    Arkangel

    01/28/2021, 10:51 AM
    Hey guys.. how can i get the remote address of a caller in ktor?
    a
    • 2
    • 6
  • e

    edenman

    01/28/2021, 7:52 PM
    ResponseException
    has an
    HttpResponse
    on it, but it looks like by the time I
    catch
    that exception, the response has already been consumed. I want to parse the json on the response, what’s the best way to do that?
    r
    • 2
    • 8
  • r

    robnik

    01/29/2021, 1:23 AM
    Is there a way to uninstall a module/routes so that I can create something like a servlet container? In other words, I'd watch for jar changes and reload an 'app' without shutting down the ktor process?
    j
    • 2
    • 3
  • c

    Cheenu Soni

    01/29/2021, 2:29 AM
    Hi, I keep getting this error
    Could not get unknown property 'kotlin_serialization' for object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.
    while importing this dependency
    implementation "org.jetbrains.kotlinx:kotlinx-serialization-core:$kotlin_serialization"
    t
    • 2
    • 5
  • c

    Cheenu Soni

    01/29/2021, 7:37 AM
    How do I store large strings in SQL? I am working with H2 database in Exposed
    :google: 2
    :stackoverflow: 2
    m
    • 2
    • 8
  • h

    hellman

    01/29/2021, 3:25 PM
    I’m not sure if I understand how to use Ktor properly. Unless I get an HTTP 200 Ok, it throws an exception unless I set
    expectSuccess
    to
    false
    . But if I do that, I can’t get the deserialized body. This means that when I get a valid response, like
    302 Found
    , I still get an exception. How is this meant to be used?
    r
    • 2
    • 23
  • a

    Allen Eubank

    01/29/2021, 4:48 PM
    Hi, friends. I’m working on a ktor server and am having trouble refactoring this bit of code. I want to move this bit of Authentication code into another file/class, specifically the validate credentials call. But I’m having a bit of trouble with the kotlin syntax. Any tips to point me in the right direction? Or more generally, is there a way to move the install features calls into separate files?
    /** Application.main() */
    val db: SqlDelightDatabase by inject()
    val orgDb: OrgDb by inject()
    
    install(Authentication) {
        basic(name = "orgtoken") {
            validate { credentials ->
                if (credentials.name.isEmpty() or credentials.name.isEmpty()) return@validate null
                val org = db.organizationQueries.selectByHttpAuthUsername(credentials.name)
                    .executeAsOneOrNull() ?: return@validate null
                val orgQueries = orgDb.instance(org) ?: return@validate null
                val activeToken = orgQueries.tokenQueries.validToken(credentials.password).executeAsOne()
    
                if (activeToken) {
                    return@validate OrganizationPrincipal(org)
                } else {
                    return@validate null
                }
            }
        }
    }
    • 1
    • 1
  • p

    Poohrang

    01/29/2021, 7:49 PM
    When I create new project with ktor in IntelliJ IDE, I encountered issue like below. It doesn't work properly even though I tried to create project in many times. Anyone knows why it's happening? My environment 1. IntelliJ IDE 211.4961.33 (Latest version) 2. ktor_version : 1.5.1 3. kotlin_version : 1.4.21 4. Project SDK : Java 15
    r
    • 2
    • 1
  • r

    Rohde Fischer

    01/30/2021, 2:07 PM
    I made a fairly small ktor project and am now trying to add Locations, but the second it's on the classpath (doesn't change if I install or don't) I get the following:
    Exception in thread "main" java.lang.AbstractMethodError: io.ktor.server.engine.ApplicationEngineEnvironmentReloading.getDevelopmentMode()Z
    	at io.ktor.application.Application.<init>(Application.kt:20)
    	at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.instantiateAndConfigureApplication(ApplicationEngineEnvironmentReloading.kt:269)
    	at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.createApplication(ApplicationEngineEnvironmentReloading.kt:125)
    	at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.start(ApplicationEngineEnvironmentReloading.kt:245)
    	at io.ktor.server.netty.NettyApplicationEngine.start(NettyApplicationEngine.kt:126)
    	at io.ktor.server.netty.EngineMain.main(EngineMain.kt:26)
    not sure where to go from here? This error isn't that descriptive
    c
    • 2
    • 12
  • c

    Cheenu Soni

    02/01/2021, 3:46 AM
    Where do I deploy my REST APIs in Ktor? Google cloud has so many hidden charges and its very confusing, and Heroku gets expensive rapidly as we scale. Are there any other options? Thanks.
    b
    a
    j
    • 4
    • 11
  • r

    Rohde Fischer

    02/01/2021, 7:36 AM
    so how do I structure a KTor app in a reasonable way with a DI? I seems I'm currently fighting the framework due it's heavy use of extension methods (I am also highly skeptical of that design choice, but for now I will go with the flow and give it a chance to grow). Say I have a
    FooRoute
    and want to make use of the
    FooService
    interface, what is a reasonable way to do that? Currently I'm around:
    class FooRoute @Inject constructor(application: Application, foo: FooService) {
        init {
            // do "magic" here
        }
    }
    but I also want to structure my code in nicely designed methods etc. so there's a clear structure to it and all that
    b
    j
    • 3
    • 22
  • i

    Ifvwm

    02/01/2021, 9:59 AM
    I tried to turn a python request RESTFul code to ktor, it's upload file with form data, but there's an error in ktor, please help https://paste.ubuntu.com/p/rmMM3W82HR/
    e
    • 2
    • 5
  • m

    melatonina

    02/01/2021, 10:10 AM
    I'm trying to use an object (singleton) to share state between a JavaFX application and a ktor netty embedded server. Two instances of the singleton are being created: one when the netty server accesses the "singleton" and one when the main application accesses it. Can you help me understand why that is happening?
    e
    b
    • 3
    • 20
  • j

    Jgafner

    02/01/2021, 3:10 PM
    Hi what is the suggested way to implement a schedule task in ktor ?
    j
    • 2
    • 2
  • e

    Evan

    02/02/2021, 12:52 AM
    has anyone used Espresso to test Android UX that’s backed by a multiplatform ktor client? I’m trying to use Espresso to verify that a response is rendered on the screen, my test starts and I call
    ktorClient.get<Something>
    and see the request logged, but the ktor client gets blocked and the ktor function never returns. As such the test hangs forever. The application runs fine normally.
    j
    • 2
    • 2
  • a

    Azur Haljeta

    02/02/2021, 3:11 PM
    HttpResponseValidator{}
    doesn't work anymore in 1.5.0, why? It doesn't get called at all https://ktor.io/docs/response-validation.html
    r
    • 2
    • 13
  • h

    hhariri

    02/03/2021, 11:51 AM
    📣 New EAP Program open, along with new plugin and plans moving forward with IDE support 📣 https://blog.jetbrains.com/ktor/2021/02/03/say-hello-to-ktor-early-access-program-and-new-plugin/
    :kotlin-intensifies: 7
    👍 9
    :ktor: 2
    c
    o
    i
    • 4
    • 11
  • b

    Big Chungus

    02/03/2021, 2:28 PM
    I'm at a complete loss with this random problem I'm facing (google didn't provide anything useful). I'm working on a fullstack project which has: • ktor-client-js & ktor-client-serialization @ 1.5.1 (js) • kotlinx.serialization-json @1.0.1 (common) The following class in commonMain:
    import kotlinx.serialization.*
    
    @Serializable
    data class PagedResponse<T>(
      val data: List<T>,
      val total: Int,
      val next: String?,
      val prev: String?,
    )
    And when I fetch something from the backed via ktor client I get this (request itself is successful and that same class is serialized on the backand fine):
    ERROR[]: Can't find a method to construct serializer for type PagedResponse. Make sure this class is marked as @Serializable or provide serializer explicitly.
    Any ideas anyone?? I'm completely lost...
    j
    s
    • 3
    • 8
  • h

    hhariri

    02/03/2021, 5:24 PM
    For folks that were wondering why we stopped publishing to JCenter, here’s one of the reasons https://jfrog.com/blog/into-the-sunset-bintray-jcenter-gocenter-and-chartcenter/
    🎉 2
    😲 7
    n
    • 2
    • 2
  • o

    Orhan Tozan

    02/03/2021, 10:34 PM
    On Android, what engine do you guys use for your ktor client? I'm currently using the Android engine, but thinking about switching to CIO. Curious what people generally like to use.
    e
    j
    • 3
    • 4
  • j

    Jgafner

    02/04/2021, 9:55 AM
    Hi Anyone know about a server feature for cache functionality ?
    j
    j
    j
    • 4
    • 7
  • a

    andylamax

    02/05/2021, 7:13 AM
    Hello, the code below for Ktor MockEngine for 1.5.1
    val client = HttpClient(MockEngine) {
                engine {
                    addHandler { request ->
                        val body = request.body
                        val req = body.toByteArray().decodeToString()
                        println(req)
                        respond("Testing", headers = responseHeaders)
                    }
               }
    }
    
    val res = client.get<String>("/")
    expect(res).toBe("test")
    throws
    io.ktor.utils.io.ByteChannelCtorKt.ByteReadChannel([B)Lio/ktor/utils/io/ByteReadChannel;
    java.lang.NoSuchMethodError: io.ktor.utils.io.ByteChannelCtorKt.ByteReadChannel([B)Lio/ktor/utils/io/ByteReadChannel;
    	at io.ktor.client.engine.mock.MockUtilsKt.respond(MockUtils.kt:74)
    	at io.ktor.client.engine.mock.MockUtilsKt.respond$default(MockUtils.kt:72)
    	at CreateEndpointTest$should_have_a_valid_path$1$client$1$1$1.invokeSuspend(CreateEndpointTest.kt:35)
    	at CreateEndpointTest$should_have_a_valid_path$1$client$1$1$1.invoke(CreateEndpointTest.kt)
    	at CreateEndpointTest$should_have_a_valid_path$1$client$1$1$1.invoke(CreateEndpointTest.kt)
    	at io.ktor.client.engine.mock.MockEngine.execute(MockEngine.kt:61)
    When executed on JVM And throws
    e: java.lang.IllegalStateException: Deserializer for declaration public <http://io.ktor.utils.io/ByteReadChannel%7C8179199761482737139[0]|io.ktor.utils.io/ByteReadChannel|8179199761482737139[0]> is not found
            at org.jetbrains.kotlin.backend.common.serialization.KotlinIrLinker.handleNoModuleDeserializerFound(KotlinIrLinker.kt:471)
            at org.jetbrains.kotlin.backend.common.serialization.KotlinIrLinker$IrDeserializerForFile.findModuleDeserializer(KotlinIrLinker.kt:359)
            at org.jetbrains.kotlin.backend.common.serialization.KotlinIrLinker$IrDeserializerForFile.deserializeIrSymbolData(KotlinIrLinker.kt:388)
            at org.jetbrains.kotlin.backend.common.serialization.KotlinIrLinker$IrDeserializerForFile.deserializeIrSymbol(KotlinIrLinker.kt:404)
            at org.jetbrains.kotlin.backend.common.serialization.IrFileDeserializer.deserializeIrSymbolAndRemap(IrFileDeserializer.kt:144)
            at org.jetbrains.kotlin.backend.common.serialization.IrFileDeserializer.deserializeCall(IrFileDeserializer.kt:387)
            at org.jetbrains.kotlin.backend.common.serialization.IrFileDeserializer.deserializeOperation(IrFileDeserializer.kt:897)
            at org.jetbrains.kotlin.backend.common.serialization.IrFileDeserializer.deserializeExpression(IrFileDeserializer.kt:938)
            at org.jetbrains.kotlin.backend.common.serialization.IrFileDeserializer.deserializeMemberAccessCommon(IrFileDeserializer.kt:345)
            at org.jetbrains.kotlin.backend.common.serialization.IrFileDeserializer.deserializeCall(IrFileDeserializer.kt:404)
    When executed on jsBrowser Am I missing a dependency?
    • 1
    • 1
  • i

    Ivan

    02/05/2021, 11:21 AM
    Hi folks. I need to retrive the Principal entity from an implementation of a function from an abstract java class provided by an external library. I can't implement this function as a suspend function and so i can't access to the coroutine context. Do you have any suggestion?
    w
    • 2
    • 1
Powered by Linen
Title
i

Ivan

02/05/2021, 11:21 AM
Hi folks. I need to retrive the Principal entity from an implementation of a function from an abstract java class provided by an external library. I can't implement this function as a suspend function and so i can't access to the coroutine context. Do you have any suggestion?
w

waltermcq

02/17/2021, 10:00 PM
Perhaps #coroutines would have a workaround?
View count: 4