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

    bbaldino

    04/29/2020, 9:42 PM
    Sorry for what's likely a dumb question, but I haven't been able to grok it from searching around: if I have an existing jetty server and want to add a ktor app as a javax servlet, how do I do that? I see lots of docs talking about deploying to jetty, but I'm confused how it actually works. I see reference to filling out reference.conf, but I don't follow how that would work. I also found
    JettyApplicationEngine
    , but didn't find much on how to use it.
    • 1
    • 2
  • g

    Grantas33

    04/30/2020, 1:06 PM
    Is it possible to specify multiple types to return from a httpClient's request depending whether the request succeeded (status code 200+) or failed (status code 300-500+)?. This is with JsonFeature configured and the server returning application/json content type.
    e
    p
    • 3
    • 3
  • i

    Ivan Brko

    04/30/2020, 4:42 PM
    Hi all, I am using ktor with kotlinx.serialization (for a server application), and I am not much familiar with neither one of those. I have a data class that has a field of type LocalDateTime, it doesn't have a default serializer so I wrote it, but is there a way I could register a serializer in ktor for a class so that I don't always have to write the following when some data class has a property of that type?
    @Serializable(with = LocalDateTimeSerializer::class)
    g
    • 2
    • 2
  • h

    Henry

    04/30/2020, 5:32 PM
    Not sure if this is allowed but would appreciate some feedback on a fun little problem I was working on https://henrycourse.com/2020/04/30/async-caching-in-ktor-with-a-minor-detour/
    j
    • 2
    • 3
  • m

    maxmello

    04/30/2020, 6:12 PM
    I installed the Timeout feature of the Ktor HttpClient, because I have some specific request that might take a long time, so I installed the feature:
    httpClient = HttpClient(CIO) {
            install(HttpTimeout) {
                requestTimeoutMillis = 60000
            }
            engine {
                maxConnectionsCount = 10000 
                endpoint.apply {
                    maxConnectionsPerRoute = 1000 
                    pipelineMaxSize = 100
                    keepAliveTime = 5000 
                    connectTimeout = 5000 
                    connectRetryAttempts = 3
                }
            }
    }
    and in my request, I specifically overwrite the requestTimeout:
    <http://httpClient.post|httpClient.post><MyResponse> {
                        url(myUrl)
                        contentType(ContentType.Application.Json)
                        timeout {
                            requestTimeoutMillis = TimeUnit.MINUTES.toMillis(30)
                        }
                        body = myBody
    }
    But I still got a coroutine
    TimeoutCancellationException
    after 15 seconds. I then specified the engine.endpoint.requestTimeout to be longer and the Exception went away - so am I not able to overwrite the CIO engines timeout with the Timeout feature? By the Timeout feature documentation, a
    HttpRequestTimeoutException
    should be thrown, not a Coroutine timeout exception, so it appears to get ignored. Can I overwrite the request timeout for CIO for a specific request? Or should I increase the CIO timeout a lot and then use the HttpTimeout feature to reduce it again?
    e
    j
    • 3
    • 3
  • c

    Colton Idle

    05/01/2020, 2:58 AM
    Caching is super important. I've only worked on mobile (android) and although I understand the basics of http, I'm really just now diving into headers and caching specifically. At the same time I'm learning a bit of backend development with ktor and I really want to nail my caching mechanism. It seems silly to me that so many backend systems don't have caching setup properly. I've read that there are ways to just use timestamps or tokens so that a server doesn't send you the same damn data again. Going off of this though, as a super new "backend" dev does anyone have any seminal talks or blog posts on the subject? Thank you
    d
    • 2
    • 2
  • i

    Imran

    05/01/2020, 8:57 AM
    any signup/login example of ktor with mongodb ?
    j
    • 2
    • 3
  • j

    John O'Reilly

    05/01/2020, 4:46 PM
    Is it possible to use Ktor WebSocket client library in Kotlin/Native (as part of KMP project)?
    b
    k
    • 3
    • 3
  • i

    Ivan Brko

    05/02/2020, 5:52 AM
    Hi all, I am playing with Ktor and I can't get the routes (for custom features I'm implementing) in right order, I would be grateful for any help or links to more informations about how route pipelines are merged. Basically I am using built-in authentication and I want to add my own authorization. This is how I'm testing it in the routing code:
    authenticate{
      minimalRoleAllowed(Role.Admin) { //this is the call to my custom feature for authorization
        get{
          ...
        }
      }
    }
    So what I would expect here to happen is have authentication called, and then if it passes have authorization called. But it seems, somehow, that when all the pipelines are merged authorization gets called before authentication, which is of course wrong, because I can't authorize the user if I they are not authenticated. This is the implementation for my
    minimalRouteAllowed
    extension method:
    fun Route.minimalRoleAllowed(role: Role, build: Route.() -> Unit): Route {
        val authorisedRoute = createChild(AuthorisedRouteSelector()) //AuthorisedRouteSelector just returns a selector which evaluates to RouteSelectorEvaluation.Const
    
        application.feature(RoleAuthorization).interceptPipeline(authorisedRoute, role)
    
        authorisedRoute.build()
        return authorisedRoute
    }
    And this is how I'm inserting phase and intercepting in the
    RoleAuthorization.interceptPipeline
    called above (the
    pipeline
    here is
    authorizedRoute
    I sent in method above):
    pipeline.insertPhaseAfter(ApplicationCallPipeline.Features, authorizationPhase)
    pipeline.intercept(authorizationPhase) {...
    • 1
    • 1
  • n

    Nikola Milovic

    05/02/2020, 10:28 AM
    Can Ktor be used as a game server to manage user data, authentication and such?
    b
    • 2
    • 1
  • l

    louiscad

    05/02/2020, 1:35 PM
    Familiar with OkHttp and retrofit, I tried to give ktor client a try but I'm now giving up for the following reasons: 1. I failed to find how to find out what kind of `Throwable`s an http call can throw (for Retrofit, it's HttpException, IOException, and RuntimeException from custom converters, interceptors or authenticator), which is a big deal as I don't want to show "unknown error" to the user and be clueless as to the call failure root cause. 2. I didn't find how I can set a pipeline "middleware" that can detect some errors (like HTTP 401), do an operation (e.g. attempt to refresh the token), and then retry the call without the initial caller having to retry. I mean, unless I do it using OkHttp authenticator, but that forces me to stick to the OkHttp engine while I wanted to try
    CIO
    , and going multiplatform. It seems to me that ktor sever doc got a lot more love than ktor client. If that's really the case, is reducing that imbalance planned?
    ❤️ 2
    d
    e
    • 3
    • 3
  • w

    waltermcq

    05/02/2020, 9:28 PM
    if JDBC is blocking, what is the benefit of using coroutines for async database calls through exposed w/ postgres?
    d
    n
    m
    • 4
    • 7
  • j

    Jitesh

    05/03/2020, 12:26 PM
    2020-05-03 17:46:18.630 [main] DEBUG com.zaxxer.hikari.HikariConfig - HikariPool-1 - configuration:
    2020-05-03 17:46:18.634 [main] DEBUG com.zaxxer.hikari.HikariConfig - allowPoolSuspension.............false
    2020-05-03 17:46:18.635 [main] DEBUG com.zaxxer.hikari.HikariConfig - autoCommit......................false
    2020-05-03 17:46:18.635 [main] DEBUG com.zaxxer.hikari.HikariConfig - catalog.........................none
    2020-05-03 17:46:18.635 [main] DEBUG com.zaxxer.hikari.HikariConfig - connectionInitSql...............none
    2020-05-03 17:46:18.635 [main] DEBUG com.zaxxer.hikari.HikariConfig - connectionTestQuery.............none
    2020-05-03 17:46:18.635 [main] DEBUG com.zaxxer.hikari.HikariConfig - connectionTimeout...............30000
    2020-05-03 17:46:18.635 [main] DEBUG com.zaxxer.hikari.HikariConfig - dataSource......................none
    2020-05-03 17:46:18.635 [main] DEBUG com.zaxxer.hikari.HikariConfig - dataSourceClassName.............none
    2020-05-03 17:46:18.635 [main] DEBUG com.zaxxer.hikari.HikariConfig - dataSourceJNDI..................none
    2020-05-03 17:46:18.675 [main] DEBUG com.zaxxer.hikari.HikariConfig - dataSourceProperties............{password=<masked>}
    2020-05-03 17:46:18.675 [main] DEBUG com.zaxxer.hikari.HikariConfig - driverClassName................."org.postgresql.Driver"
    2020-05-03 17:46:18.675 [main] DEBUG com.zaxxer.hikari.HikariConfig - healthCheckProperties...........{}
    2020-05-03 17:46:18.675 [main] DEBUG com.zaxxer.hikari.HikariConfig - healthCheckRegistry.............none
    2020-05-03 17:46:18.675 [main] DEBUG com.zaxxer.hikari.HikariConfig - idleTimeout.....................600000
    2020-05-03 17:46:18.675 [main] DEBUG com.zaxxer.hikari.HikariConfig - initializationFailTimeout.......1
    2020-05-03 17:46:18.675 [main] DEBUG com.zaxxer.hikari.HikariConfig - isolateInternalQueries..........false
    2020-05-03 17:46:18.676 [main] DEBUG com.zaxxer.hikari.HikariConfig - jdbcUrl.........................jdbc:postgresql:testDB?user=postgres;
    
    2020-05-03 17:46:18.683 [main] INFO  com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Starting...
    2020-05-03 17:46:18.736 [main] DEBUG com.zaxxer.hikari.pool.PoolBase - HikariPool-1 - Failed to create/setup connection: FATAL: role "postgres;" does not exist
    2020-05-03 17:46:18.737 [main] DEBUG com.zaxxer.hikari.pool.HikariPool - HikariPool-1 - Cannot acquire connection from data source
    s
    m
    • 3
    • 3
  • c

    codec

    05/05/2020, 4:42 AM
    I also have a question about authentication. When a user logs out, how do we invalidate the UserIdPrincipal and clear out the UserPasswordCredential?
    c
    • 2
    • 7
  • g

    Giovanni Alluvatti

    05/05/2020, 9:52 AM
    Hello there! I have a question on how to test e2e (making rest calls) a ktor+kodein application. The test should be included in the application project. I can explain better with a comparison to spring boot since I'm migrating from it. In Spring Boot I can create a test annotated with
    @SpringBootTest
    , starting up my application with a real context (no mocks); then using a
    TestRestTemplate
    I can call my rest api exposed to
    <http://localhost>:{springBootRandomPort}
    . Does anybody know a similar smart way to test this scenario also for a ktor + kodein app? Unfortunately I wasn't able to find any examples on official documentation.
    c
    • 2
    • 2
  • m

    melatonina

    05/05/2020, 11:49 AM
    Hello. I may need to switch back from Kotlin 1.3.72 to 1.3.61. Which version of Ktor should I use with Kotlin 1.3.61? Is it Ktor 1.3.1?
    j
    • 2
    • 1
  • i

    Ivan Brko

    05/06/2020, 2:31 PM
    Hi all, I am trying to add swagger to a Ktor application and I found https://github.com/nielsfalk/ktor-swagger and it seems nice, but not really active. Do people use this project, as I can see that there are opened PRs from months ago and that version of the lib for Ktor 1.3 hasn't been released yet? Does anyone know if the author has given up on the library or just doesn't have enough time to work on it lately?
    d
    s
    • 3
    • 6
  • d

    Dias

    05/06/2020, 3:25 PM
    I am asking, because at some point something in my app stops making http calls and it's not obvious where that happens, I am not using coroutines, just
    httpClient.get<HttpResponse>(...)
    . I doesn't look that httpresponse needs to be closed, but maybe I am leaking resources somewhere?
    :thread-please: 1
    d
    • 2
    • 4
  • h

    Henry

    05/07/2020, 8:01 AM
    basic one but what's the best pattern for accessing config in top level functions (or is this just not the way to do things)? e.g.
    fun fetchInternalClientInstance() { ...I need access to application.config in here...}
    on a wider point could anyone link me to some resources discussing higher level application architecture with ktor as I'm starting to get beyond what is covered by the Youkube example?
    👍 2
    d
    m
    • 3
    • 39
  • i

    Ivan Brko

    05/07/2020, 12:51 PM
    Asked i serialization channel, nobody replied, maybe someone knows here: Does anyone know if I can somehow register a serializer in ktor (using kotlinx.serialization)? I am writing a Ktor sever and I need to return a data class from a 3rd party library, so I can't annotate it with @Serializable. I can write a serializer for it, but how to tell Ktor to use this serializer?
    d
    • 2
    • 16
  • b

    bitkid

    05/07/2020, 3:14 PM
    Hi! Is there a specific reason why exceptions thrown in
    call.respondOutputStream{ throw BlaException()}
    are not recoverable, meaning that they dont get propagated to the status pages handler?
    m
    • 2
    • 3
  • n

    Nikky

    05/07/2020, 8:35 PM
    how likely is the Locations api (type-safe routing) to be removed ? since the
    @KtorExperimentalLocationsAPI
    warns about that
    d
    • 2
    • 4
  • m

    Matthieu Stombellini

    05/07/2020, 10:55 PM
    Hi everyone. I need to test some user routes in an app that I'm building. These endpoint use a (header-based) session. My question is, how can I tell the sessions feature to "create" a session before calling that user endpoint? What I'm doing right now is calling the actual logging-in endpoint to set up the session properly and using the header that that returns.
    n
    • 2
    • 1
  • n

    Nikky

    05/08/2020, 10:10 AM
    is there any way to use
    kotlin.serialization
    for the Sessions feature? in particular how the data class is turned into some sort of string.. whni i extend
    SessionStorage
    to store those strings in postgres, i would like to have json or structured data instead of however it serializes fields
    c
    • 2
    • 5
  • r

    Rodrigo Silva

    05/09/2020, 7:26 PM
    Can i create my own oauth2 server with ktor?
    c
    s
    • 3
    • 4
  • k

    Kirill Prybylsky

    05/10/2020, 2:15 PM
    Hello everyone, I am trying to implement websocket feature with ktor, but I only get 404 for the http://localhost:8080/ request in browser. Could you, please, tell me what can be wrong? Here is my websocket implementation:
    webSocket("/") {
        while (true) {
            delay(3000)
            outgoing.send(Frame.Text("hi"))
        }
    }
    r
    • 2
    • 9
  • m

    Mario Trucco

    05/10/2020, 2:57 PM
    Hey everyone! I believe that this is a bug:
    scheme
    returned instead of
    version
    . Is it ok if I open an issue and link it in a fix PR?
    r
    • 2
    • 1
  • r

    Robin Larsen

    05/10/2020, 9:21 PM
    Hi! I'm trying to decide whether to go with Firebase for user authentication or with the Ktor features, namely Sessions and Authentication (JWT). However, I haven't been able to find some good guides on Firebase Admin and Ktor integration, which makes it harder to go down that route. But at the same time, I'm and Android developer, so I don't know that much about web, and I'd feel more comfortable delegating the responsibility to Firebase if the implementation is simple. Anyone know whether it's worthwhile/possible to make Ktor work with Firebase? And possibly link some guides?
    e
    d
    • 3
    • 4
  • r

    rudolf.hladik

    05/11/2020, 8:36 AM
    Hi everyone, is there a snapshot of ktor client which uses native-mt coroutines?
    j
    • 2
    • 1
  • d

    david.bilik

    05/12/2020, 6:22 AM
    hi, I have a weird problem with dependencies resolution while using
    auth
    artifact. This is my build.gradle
    plugins {
        id 'java'
        id 'org.jetbrains.kotlin.jvm' version '1.3.72'
    }
    
    apply plugin: 'java'
    
    repositories {
        jcenter()
    }
    
    dependencies {
        implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
        def ktor_version = '1.3.0'
        implementation "io.ktor:ktor-client-okhttp:$ktor_version"
        implementation "io.ktor:ktor-client-gson:$ktor_version"
        implementation "io.ktor:ktor-client-auth:$ktor_version"
        implementation "io.ktor:ktor-client-logging:$ktor_version"
    }
    
    compileKotlin {
        kotlinOptions.jvmTarget = "1.8"
    }
    and I am trying to use Basic authentication when making a request from the client but
    import io.ktor.client.features.auth.Auth
    is not resolved in the IDEA even though I can see it in external libraries in the project structure. I thought that it can be related with gradle version, but I’ve updated to 6.1.1 and nothing changed
    • 1
    • 1
Powered by Linen
Title
d

david.bilik

05/12/2020, 6:22 AM
hi, I have a weird problem with dependencies resolution while using
auth
artifact. This is my build.gradle
plugins {
    id 'java'
    id 'org.jetbrains.kotlin.jvm' version '1.3.72'
}

apply plugin: 'java'

repositories {
    jcenter()
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
    def ktor_version = '1.3.0'
    implementation "io.ktor:ktor-client-okhttp:$ktor_version"
    implementation "io.ktor:ktor-client-gson:$ktor_version"
    implementation "io.ktor:ktor-client-auth:$ktor_version"
    implementation "io.ktor:ktor-client-logging:$ktor_version"
}

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
and I am trying to use Basic authentication when making a request from the client but
import io.ktor.client.features.auth.Auth
is not resolved in the IDEA even though I can see it in external libraries in the project structure. I thought that it can be related with gradle version, but I’ve updated to 6.1.1 and nothing changed
Looks like using artifact
"io.ktor:ktor-client-auth-jvm:$ktor_version"
helps but is it necessary?
View count: 4