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

    Adriano Celentano

    10/11/2019, 9:18 AM
    My question can be reduced to: are there other certificate types supported by ktor than .jks ?
    s
    • 2
    • 1
  • j

    janvladimirmostert

    10/12/2019, 5:14 AM
    is there a way in Ktor to do a 301 redirect from www.domain.com to domain.com ? tried doing that 301 redirect at the DNS level and it seems to cause SSL errors.
    • 1
    • 2
  • v

    Vinicius Araujo

    10/12/2019, 11:26 PM
    How to install a feature after Authentication phase so I can use a Principal? Tried this without success:
    companion object Feature : ApplicationFeature<ApplicationCallPipeline, Configuration, Permission> {
            override val key = AttributeKey<Permission>("Permissions")
    
            override fun install(pipeline: ApplicationCallPipeline, configure: Configuration.() -> Unit): Permission {
                val configuration = Configuration().apply(configure)
                val feature = Permission(configuration)
                val permissionPhase = PipelinePhase("PermissionPhase")
    
                pipeline.insertPhaseAfter(PipelinePhase("RequestAuthentication"), permissionPhase)
    
    
                pipeline.intercept(permissionPhase) {
                    feature.intercept(this)
                }
    
                return feature
            }
        }
    👆 1
    e
    • 2
    • 4
  • j

    Jan Stoltman

    10/13/2019, 6:56 PM
    Hey guys, I'm writing a multiplatform client app with ktor using OkHttp on Android and Ios on iOS. I would like to be able to catch and handle all connection related exceptions (eg.
    SocketTimeoutException
    ,
    UnknownHostException
    on Android) in my common code, but propagate any other exception. Is there a way to solve my problem ktor?
    b
    • 2
    • 1
  • c

    cmgurba

    10/14/2019, 9:05 PM
    is there a known issue with not catching child exceptions with StatusPages? I've expanded my exception declaration out to
    Throwable
    (also tried
    Exception
    ) and can't seem to get it hit my configured exception code still... currently on ktor
    1.1.4
    • 1
    • 1
  • s

    Santosh Astagi

    10/15/2019, 1:06 AM
    If I install KotlinxSerializer for Jdd sad onFeature for ktor, is there a place I can catch kotlinx.SerializationException?
    d
    • 2
    • 2
  • r

    ribesg

    10/15/2019, 1:36 PM
    I’m encountering this error. The report is more than a year old. Why hasn’t this been fixed? https://github.com/ktorio/ktor/issues/601 So Locations just don’t work right now and haven’t been working for a year?
    e
    • 2
    • 2
  • a

    adeln

    10/16/2019, 11:40 AM
    hey folks! I’m trying to set a secure flag to my cookies, and I’m getting
    java.lang.IllegalArgumentException: You should set secure cookie only via secure transport (HTTPS)
    I’m running ktor on http, and proxying it through http/2 nginx. Is there a way to solve this?
    j
    m
    s
    • 4
    • 16
  • j

    jfburdet

    10/16/2019, 4:15 PM
    Hi, I need some help. I'm using ktor server to build a REST server. I'm using jackson ContentNegotiation and everything is fine. Except now I want that some of my routes answer sometime an image. But event I'm setting the ContentType in my response (call.respondBytes(resultFile.readBytes(), ContentType("image", "png"))) I see that actual headers are still "application/json" ... How can I tweak ktor to not override contentType when I'm explicitly setting it in my response ?
    j
    • 2
    • 4
  • s

    Shan

    10/16/2019, 5:59 PM
    Does anyone know the reasoning behind Ktor (with Kotlinx.Serialization JsonFeature) trying to use reflection to find the serializer generated when annotating something with
    @Serialized
    when it always generates a KSerializer every time? I am explicitly setting it with
    setMapper(KClass, KSerializer)
    right now, but am wondering if there is a way to have it detect it as the KSerializer will always be there (to my knowledge).
    l
    • 2
    • 3
  • s

    Scott Dillender

    10/16/2019, 6:59 PM
    Is there a way to grab the current authentication/principal outside of the context of an Application.call. Would the only way to do this be to store it as a ThreadLocal and implement a ThreadContextElement to copy into appropriate coroutines?
    e
    m
    • 3
    • 19
  • j

    Jorge R

    10/17/2019, 3:45 PM
    Hi all, I’ve implemented MicrometerMetrics in my backend + Prometheus to do the pulling from a GET /metrics endpoint and so far it works fine. The problem with this implementation is that it is not scalable (not sure if Prometheus has autodiscovery). Do you know any other way of implementing metrics that is not requiring pull from Prometheus but using push from each backend instance to a elastic search container?
    l
    j
    • 3
    • 3
  • s

    Shan

    10/17/2019, 10:46 PM
    I get this error:
    Request of type HttpMethod(value=GET) couldn't send a body with the Android engine.
    I see that specifically on the Android engine I cannot send a GET request with an empty body but am unsure of the reasoning for this.
    e
    • 2
    • 3
  • s

    Santosh Astagi

    10/17/2019, 11:34 PM
    The HttpClientEngine in ktor has a close method, when is that supposed to be used?
    ➕ 1
    e
    • 2
    • 1
  • s

    Shan

    10/18/2019, 7:52 PM
    Does anyone have an example of using Ktor + Kotlinx.Serialization when getting a JsonArray back as a response? I see the
    setListMapper()
    and
    registerList<>()
    functions as part of the JsonFeature, but am unsure of how to use them, or if they are even applicable in the case of getting back an array response. Just trying to test it in a test project at the moment, this is what I have. Does my array need to be within the
    @Serializable
    data class itself? The format of the response is:
    [
        {
            id: 382910,
            name: "name",
            isEnabled: true
        },
        {
            //etc..
        }
    ]
    I get this error:
    Can't locate argument-less serializer for interface java.util.List (Kotlin reflection is not available). For generic classes, such as lists, please provide serializer explicitly.
    which makes sense but I also believe there is a way to do this without writing a custom serializer, I just can't find the info anywhere.
    Untitled
    d
    • 2
    • 8
  • l

    lewis

    10/19/2019, 11:04 AM
    Is there a way to handle unresolved routes? I'm writing an SPA that uses HTML5 history - which requires all unresolved routes to serve /
    w
    a
    • 3
    • 8
  • n

    Nikky

    10/19/2019, 5:03 PM
    using static content https://ktor.io/servers/features/static-content.html can i do
    static("/")
    and access files from the root of the jar ? it seems like when i do that the requests do not match
    w
    • 2
    • 4
  • r

    Ruckus

    10/21/2019, 2:26 PM
    I apologize if this has been asked before, but I'm having trouble figuring out what to search for. Is Ktor meant primarily to be a web based library, or is it a good fit for other connected uses (e.g. controlling DMX devices)?
    g
    s
    f
    • 4
    • 7
  • s

    Szymon Lipiński

    10/21/2019, 6:50 PM
    Hey, is there a good example of a ktor application with jdbc connection pooling?
    j
    m
    • 3
    • 7
  • c

    coder82

    10/22/2019, 11:43 AM
    Using the Authentication feature, is there a way to get the credentials during a normal call, I must check if a specific user is allowed to can a specific api or not....
    d
    b
    j
    • 4
    • 8
  • s

    Steve Young

    10/22/2019, 3:54 PM
    How should I use httpClientCall.cancel()? It seems to be only canceling the current job, so it cannot be done asynchronously
    e
    • 2
    • 5
  • s

    Santosh Astagi

    10/22/2019, 8:41 PM
    but I get this as a list, so don't want to build it here, but pass in a list
    e
    • 2
    • 28
  • m

    mantono

    10/23/2019, 9:50 PM
    I saw that there was a pull request for a rate limiting feature for Ktor a while ago, but it recently became closed because it got stale. I have done my own rate limiting feature. Is there a high demand for such feature in Ktor? Should I consider doing a PR?
    👍 1
    b
    j
    • 3
    • 4
  • r

    Riccardo Montagnin

    10/24/2019, 9:42 AM
    Hi guys, is there a guide on how to mock an HttpClient so that it can return proper WebSocket responses? I was only able to find the mocking guide for the server part, but not the client one
    e
    • 2
    • 6
  • l

    lewis

    10/24/2019, 11:47 AM
    Does Ktor provide a way to detect if the connection is secure (while supporting Forwarded headers)?
    • 1
    • 1
  • n

    Nikky

    10/25/2019, 4:07 PM
    i am having issues getting websockets on kotlin-js to work, it seems that on close or timeout they never run
    catch
    or any code past the websocket https://gist.github.com/NikkyAI/91cd375a24bab6301c14e281cf2d4b93 could alos be that i misunderstood how to use coroutines on js ? also it seems to work on fine on jvm
    w
    • 2
    • 3
  • n

    Nikky

    10/27/2019, 2:06 PM
    i am trying to use ping-pong and timeout on websockets with ktor.. but either chrome debugger hides those frame types.. or it does not work does anybody here have experience with that ? i am using
    install(WebSockets){
            pingPeriod = Duration.ofSeconds(5)
            timeout = Duration.ofSeconds(10)
        }
    a
    • 2
    • 2
  • j

    Jake

    10/28/2019, 6:57 PM
    I’m having some issues starting an MPP project and using KTOR for iOS. Does anyone have any experience with getting this set up properly? My issue is that I can’t seem to import the
    HttpClient
    and initialize that engine in the iOS project, I keep getting an “Unresolved Reference”. I have no issues creating the engine for Android. Here is my
    build.gradle
    plugins {
        id 'org.jetbrains.kotlin.multiplatform' version '1.3.50'
    }
    repositories {
        google()
        jcenter()
        mavenCentral()
    }
    apply plugin: 'com.android.application'
    apply plugin: 'kotlin-android-extensions'
    
    ext {
        ktor_version = "1.2.5"
    }
    
    android {
        compileSdkVersion 28
        defaultConfig {
            applicationId 'org.jetbrains.kotlin.mpp_app_android'
            minSdkVersion 15
            targetSdkVersion 28
            versionCode 1
            versionName '1.0'
            testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner'
        }
        buildTypes {
            release {
                minifyEnabled false
            }
        }
    }
    
    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        implementation 'com.android.support:appcompat-v7:28.0.0'
        implementation 'com.android.support.constraint:constraint-layout:1.1.3'
        androidTestImplementation 'com.android.support.test:runner:1.0.2'
    }
    
    kotlin {
        android("android")
        // This is for iPhone emulator
        // Switch here to iosArm64 (or iosArm32) to build library for iPhone device
        iosX64("ios") {
            binaries {
                framework()
            }
        }
        sourceSets {
            commonMain {
                dependencies {
                    implementation kotlin('stdlib-common')
                    implementation "io.ktor:ktor-client-core:$ktor_version"
                }
            }
            commonTest {
                dependencies {
            		implementation kotlin('test-common')
            		implementation kotlin('test-annotations-common')
                }
            }
            androidMain {
                dependencies {
                    implementation "io.ktor:ktor-client-core-jvm:$ktor_version"
                    implementation "io.ktor:ktor-client-apache:$ktor_version"
                    implementation kotlin('stdlib')
                }
            }
            androidTest {
                dependencies {
                    implementation kotlin('test')
                    implementation kotlin('test-junit')
                }
            }
            iosMain {
                dependencies {
                    implementation "io.ktor:ktor-client-core-native:$ktor_version"
                    implementation "io.ktor:ktor-client-ios:$ktor_version" // I saw in Maven that the last recorded version (that I could see) was 1.0.1  - I tried that too
                }
            }
            iosTest {
            }
        }
    }
    
    // This task attaches native framework built from ios module to Xcode project
    // (see iosApp directory). Don't run this task directly,
    // Xcode runs this task itself during its build process.
    // Before opening the project from iosApp directory in Xcode,
    // make sure all Gradle infrastructure exists (gradle.wrapper, gradlew).
    task copyFramework {
        def buildType = project.findProperty('kotlin.build.type') ?: 'DEBUG'
        def target = project.findProperty('kotlin.target') ?: 'ios'
        dependsOn kotlin.targets."$target".binaries.getFramework(buildType).linkTask
    
        doLast {
            def srcFile = kotlin.targets."$target".binaries.getFramework(buildType).outputFile
            def targetDir = getProperty('configuration.build.dir')
            copy {
                from srcFile.parent
                into targetDir
                include 'app.framework/**'
                include 'app.framework.dSYM'
            }
        }
    }
    e
    • 2
    • 2
  • t

    Tony

    10/30/2019, 5:57 PM
    Hello, I am having an issue with iOS memory leaks when I make a ktor get request. The dispatcher is being built on the iosX64/iosArm32/iosArm32 side through an class implementing CoroutineDispatcher() with the override fun dispatch doing
    dispatch_async(dispatch_get_main_queue()) {
        block.run()
    }
    Untitled
    e
    • 2
    • 2
  • a

    Animesh Sahu

    10/31/2019, 6:48 AM
    Is there a way to extend frame class, it is "actual sealed" in package io.ktor.http.cio.websocket, but one should not restrict to have only Text and Binary frames cuz its very hard to send packets for different-different purposes.
    e
    • 2
    • 9
Powered by Linen
Title
a

Animesh Sahu

10/31/2019, 6:48 AM
Is there a way to extend frame class, it is "actual sealed" in package io.ktor.http.cio.websocket, but one should not restrict to have only Text and Binary frames cuz its very hard to send packets for different-different purposes.
e

Evan R.

10/31/2019, 1:45 PM
No, you are not allowed to extend sealed classes
a

Animesh Sahu

10/31/2019, 1:55 PM
@Evan R. Why dont they give us ability to register custom frames with custon opcodes
e

Evan R.

10/31/2019, 3:06 PM
Because those frames and opcodes are part of the websocket specification: https://tools.ietf.org/html/rfc6455#section-5.2 It’s a low-level implementation detail. What other type of data are you trying to send over the websocket?
a

Animesh Sahu

10/31/2019, 3:38 PM
@Evan R. Like discord gateway has custom packets like that i'm trying to achieve: https://imgur.com/a/seXjUYK (see top right)
e

Evan R.

10/31/2019, 3:44 PM
Discord doesn’t have custom packets on their websocket API. According to their docs, those pieces of data like opcodes and such are just JSON encoded strings sent as the payload of the frame, so you’d be sending a payload like
{"op": 10, "d": { "heartbeat_interval": ... }
as a text frame over the websocket for the HELLO operation
a

Animesh Sahu

10/31/2019, 3:45 PM
Ohh ok thanks
e

Evan R.

10/31/2019, 3:46 PM
You might honestly be better off using a library like Discord4J rather than writing directly to a websocket: https://github.com/Discord4J/Discord4J
a

Animesh Sahu

10/31/2019, 3:48 PM
😉 thanks
e

Evan R.

10/31/2019, 3:50 PM
If you still wanna use coroutines with that library though you can use the coroutines reactive extensions: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-reactive/
View count: 1