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

    KamilH

    10/14/2020, 8:21 AM
    How are you abstracting Ktor’s
    HttpClient
    ? I would like to hide it behind interface for testing and maintainability purposes, but I can’t because its methods are defined as a
    inline reified
    g
    j
    • 3
    • 12
  • j

    Joost Klitsie

    10/14/2020, 8:44 AM
    Hi all! Are there issues with the
    HttpResponseValidator
    on Javascript? Somehow, if I have this:
    HttpResponseValidator {
        validateResponse {
            check(it.status == HttpStatusCode.OK || it.status == HttpStatusCode.NoContent)
        }
        handleResponseException {
            println("Response exception")
        }
    }
    The handleResponseException is not called, until the coroutine it is launched in cancels. Also subsequent requests are hanging
    • 1
    • 1
  • s

    Sergey Bezrukov

    10/14/2020, 3:19 PM
    Hi all, that is recommended method to generate ktor client from OpenAPI v3 specs nowadays? Ktor support in openapi-generator seems to be outdated, it uses kotlin 1.3.50/ktor 1.2.4/serialization 0.12.0.
    c
    m
    m
    • 4
    • 4
  • p

    Peter Tran

    10/14/2020, 8:00 PM
    Hi! Question about ktor and multiplatform. I see OAuth2 support is provided by the code in
    ktor-features/ktor-auth
    . However, all of the source is under
    jvm/
    . Is there a particular dependency on JVM? Or is there some other reason this cannot be common code and reused on a native platform?
    c
    • 2
    • 4
  • d

    Dávid

    10/15/2020, 8:46 AM
    Hey all. I googled and dug through docs and I am still a bit confused about this. I am trying to make an interceptor that will check if an authorized principal has rights to access a route based on roles. This is my interceptor, which I based on the one in the docs:
    fun Route.authorizedBy(roles: List<String>, callback: Route.() -> Route): Route {
        val routeWithRoles = this.createChild(object : RouteSelector(RouteSelectorEvaluation.qualityConstant) {
            override fun toString(): String {
                return "(roles: $roles)"
            }
    
            override fun evaluate(context: RoutingResolveContext, segmentIndex: Int): RouteSelectorEvaluation =
                RouteSelectorEvaluation.Constant
        })
    
        routeWithRoles.intercept(ApplicationCallPipeline.Call) {
            if (!hasAccess(roles, call.user)) {
                call.respond(HttpStatusCode.Unauthorized, "Not sufficient authority") //todo I am not sure if I should respond or throw errror
                finish() //todo i am not sure if I should call finish here
            }
        }
    
        callback(routeWithRoles)
        return routeWithRoles
    }
    1. In my code I am uncertain if I should throw an exception from the interceptor or is it ok to call the
    respond
    method? 2. Also is it necessary to call the
    finish()
    there? 3. Should I call
    proceed()
    in the
    else
    branch or is that not necessary? In general I think it is unclear when to use the proceed and finish methods and what is an intended way to break out of an interceptor with errors.
    r
    • 2
    • 5
  • h

    hhariri

    10/15/2020, 10:31 AM
    In case folks are interested about some design discussion we’re having regarding Ktor features https://youtrack.jetbrains.com/issue/KTOR-1142
    r
    • 2
    • 1
  • t

    than_

    10/15/2020, 1:09 PM
    hi, is it possible to add headers to request in servers Pipeline::intercept?
    r
    • 2
    • 1
  • r

    Rodrigo Silva

    10/15/2020, 5:02 PM
    Hi all. Using ktor-jwt how can i get the payload?
    r
    • 2
    • 2
  • m

    marios proto

    10/16/2020, 11:21 AM
    Hi. I am using Retrofit in an Android project, and want to migrate some parts to Ktor Client as a PoC. I am having trouble to find a way of getting the wrapped return value as Retrofit does. e.g.
    suspend fun get() :Response<DataValue>
    in Retrofit would give me a response code, a way to parse an error model returned, etc easily. How can I have this in Ktor? Haven't seen it in the examples, unless using the
    HttpResponseValidator
    function to the Client configuration, which I will have to configure per api call. I am pretty sure there is an easier way, but could someone point me to a good example please?
    r
    • 2
    • 2
  • p

    Philipp Karlsson

    10/16/2020, 12:07 PM
    Hi all, I try to implement an async request to a ktor-Server which shall respond directly and then start the async task. It is possible to do it like:
    put<MyRoute> {
            call.respond(HttpStatusCode.OK)
            MyService.runTask()
        }
    This returns the response directly and the synchronous task seems to run until the end. Does every call already run in a separated thread or do I have to start a new thread for the runTask()?
    c
    • 2
    • 9
  • m

    Marc Knaup

    10/16/2020, 1:40 PM
    When can we expect the next update? That Apache client engine bug keeps freezing my entire program every night 😕
    c
    • 2
    • 1
  • a

    Ali Albaali

    10/16/2020, 8:04 PM
    Hi guys, Is there a way to rerun the request when intercepting the response pipeline? I'm trying to implement a Refresh Token Feature but I can't figure a way to rerun the request with the new token.
    r
    • 2
    • 2
  • d

    dorf

    10/18/2020, 7:59 AM
    Hey, is it common practice to pass around a coroutine context? Specifically, should I pass around the
    application
    variable? I come from the C# world, and I’m trying to figure out how to actually call suspend functions
    j
    • 2
    • 1
  • r

    rsetkus

    10/18/2020, 11:55 AM
    Hi. Working on a custom Ktor feature to extend http cache-control to store on a permanent storage. Following default Ktor cache feature
    HttpCache
    implementation. Faced with some challenges and some obstacles which I cannot overcome: 1.
    HttpResponse
    and
    HttpRequest
    have few sub-classes but only
    DefaultHttpResponse
    and
    DefaultHttpRequest
    are public but they are annotated as
    @InternalAPI
    . I could use them to deserialize stored data but then it put the project at risk. However, this is not the main issue. 2. Even though, technically
    DefaultHttpResponse
    and
    DefaultHttpRequest
    are usable but they requires
    HttpClientCall
    instance. 3.
    HttpClientCall
    constructor is internal. Function with the same name
    HttpClientCall
    is internal also. So technically cannot create the object instance. Briefly,
    HttpClientCall
    is main obstacle of implementing permanent cache storage. Does anybody have any idea how to overcome this?
    👀 1
    e
    • 2
    • 1
  • j

    John Moore

    10/18/2020, 11:44 PM
    Hey all! Does anyone know where ktor.io/docs is maintained so that suggestions/PRs/etc. could be made? Is an issue report preferred?
    d
    • 2
    • 2
  • m

    manlan

    10/19/2020, 11:27 AM
    Where has this dependency gone? Intellij says it's not found.
    implementation("io.ktor:ktor-server-serialization:1.4.1")
    I'm still confused about setting up kotlinx #serialization with ktor 😩
    r
    r
    • 3
    • 42
  • n

    nikolaymetchev

    10/19/2020, 2:23 PM
    Hello everyone, I am curious to find out if I can get ktor client micrometer metrics. The ktor server has the
    MicrometerMetrics
    feature but I don’t see an equivalent one for the ktor client. Am I missing something?
    a
    • 2
    • 6
  • r

    Rui

    10/19/2020, 3:01 PM
    Hello everyone, I have a question about extracting routes. So I extracted them and put them in separate files, but the question is, if these different routing all need to hold the references to same objects, where to put those objects? More specifically, I have two routing files called Order.kt and Item.kt, and both of them need to use an instance of ItemService class. Then where should I put this
    lateinit var itemService: ItemService
    For now this is what I do, in Order.kt file:
    lateinit var itemService: ItemService
    fun Route.order() {
      post<Order> {
        init(...)
      }
    
      get<Order> {
        init(...)
      }
    }
    
    init(...) {
      itemService = ItemService(...)
    }
    and in Item.kt file
    fun Route.item() {
      post<Item> {
        init(...)
      }
      get<Item> {
        init(...)
      }
    }
    Basically I put those common objects and their initialization method in one of the routing files, and other routing file can have direct access to those objects and methods. I wonder what is the more proper way of organizing this? Appreciate any kinds of input !
    m
    • 2
    • 11
  • k

    Kris Wong

    10/19/2020, 5:37 PM
    I am still getting crashes from Ktor on iOS...
    t
    • 2
    • 8
  • c

    chucvv

    10/20/2020, 4:42 AM
    I am using Ktor to build api backend for mobile project I can not find any support from Ktor for caching Redis Do you know any suggestion ?
    m
    • 2
    • 2
  • t

    than_

    10/20/2020, 8:48 AM
    Hi, i need different caching strategies for different parts of my API. I tried to split the app into two modules and install
    CachingHeaders
    in both, just with different configuration. This fails with
    io.ktor.application.DuplicateApplicationFeatureException: Conflicting application feature is already installed with the same key
    Is this possible at all?
    r
    • 2
    • 2
  • j

    John O'Reilly

    10/20/2020, 11:41 AM
    Is there way to dynamically enable/disable particular routes? Or for example does web server have to be restarted to allow this?
    g
    • 2
    • 4
  • m

    Michael

    10/20/2020, 9:42 PM
    Are there guides that show you how to implement custom authentication? This is all I got from the official documentation which is quite lacking
    f
    j
    • 3
    • 5
  • t

    tieskedh

    10/21/2020, 10:45 AM
    Maybe a very easy question, but I couldn't find it: I want to create a test in Ktor-client that simulates that the httpClient does not have an connection. How can I do that?
    k
    • 2
    • 2
  • k

    Kris Wong

    10/21/2020, 3:07 PM
    is it possible to update the routing on the
    Applicaiton
    after the server is stated?
    j
    j
    • 3
    • 29
  • c

    Chris Fillmore

    10/21/2020, 4:37 PM
    I would like to set this on a per-request basis
    m
    • 2
    • 3
  • a

    Astronaut4449

    10/21/2020, 10:20 PM
    Does anybody know how to hot reload and refresh the browser window after a change with ktor like the web pack dev server does?
    a
    • 2
    • 2
  • c

    CLOVIS

    10/22/2020, 3:30 PM
    Hi! Is there a way to log the exact request a Ktor client is sending? Not just the headers, but also the full body contents
    r
    m
    • 3
    • 8
  • h

    HankG

    10/23/2020, 5:14 PM
    I'm trying to use Ktor under Kotlin Native but it looks like the ktor-client-core-native package doesn't exist with the 1.4 line
    h
    • 2
    • 3
  • d

    Davide Giuseppe Farella

    10/24/2020, 10:54 AM
    Good morning everyone, I’m using Ktor-client on a multiplatform project, I created an
    Either
    class, similar to the one from Arrow-kt. I’d like to know if is possible to create a “converter” for it. Thank you
    j
    • 2
    • 4
Powered by Linen
Title
d

Davide Giuseppe Farella

10/24/2020, 10:54 AM
Good morning everyone, I’m using Ktor-client on a multiplatform project, I created an
Either
class, similar to the one from Arrow-kt. I’d like to know if is possible to create a “converter” for it. Thank you
j

Javier

10/24/2020, 10:58 AM
I am interested too, I was tried some time ago and I couldn't
d

Davide Giuseppe Farella

10/24/2020, 11:03 AM
Best thing I found so far is https://ktor.io/docs/response-validation.html#configuration Usage example
class EitherException(val reason: Error)

when {
  xxx -> throw EitherException(Xxx)
  yyy -> throw EitherException(Yyy)

// Either.Compaion
fun Try(block: () -> T) =
  try { 
    Right(...)
  } catch (e: EitherException) 
    Left(...)
  }

fun login(...) = 
  Either.Try { <http://client.post|client.post>(...) }
j

Javier

10/24/2020, 11:14 AM
Yeah that can be a workaround but I would like to create a feature similar I did with Retrofit and an adapter
d

Davide Giuseppe Farella

10/24/2020, 12:56 PM
I did in this way for now https://github.com/4face-studi0/CineScout/commit/8c7e850feb742f9a23829a648344ecdb8e64c2dd
View count: 2