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

    Patrik Åkerfeldt

    09/30/2020, 9:46 AM
    I have a ktor application with routes/controllers and stuff. Now I also need a separate component which should, on startup, subscribe to a Google PubSub topic and at shutdown, unsubscribe. It also has dependencies and so it needs to have `KoinComponent`s injected. Since nobody is depending directly on this component, it's not getting created by Koin at all. What would be the idiomatic way of solving this use case in Ktor?
    • 1
    • 1
  • m

    mbonnin

    09/30/2020, 2:34 PM
    This documentation https://kotlinlang.org/docs/mobile/concurrency-and-coroutines.html#ktor-and-coroutines states:
    Make sure that you use the single-threaded version of 
    kotlinx.coroutines
     as a dependency for Ktor. Ktor for macOS and iOS requires this version.
    That seems outdated since Ktor 1.4.1 pulls
    -native-mt-2
    ? Can this be changed/should an issue be filed somewhere?
    ➕ 1
    l
    r
    +2
    • 5
    • 9
  • a

    atsushi-koshikizawa

    09/30/2020, 4:50 PM
    Will Ktor support TLS sessions (HTTPS) on native platform?
    Untitled
    c
    • 2
    • 2
  • j

    Júlio Santos

    09/30/2020, 6:03 PM
    Speak up, guys! I'm putting together a clause where exposed this way 
    Employee.select { Employee.id = id and (Employee.name = name)}
     is that correct?
    j
    • 2
    • 1
  • r

    Reprator

    09/30/2020, 7:18 PM
    Hi guys, need some help, how to invalidate a token with following code?
    package com.firstapp.auth
    
    import com.auth0.jwt.JWT
    import com.auth0.jwt.JWTVerifier
    import com.auth0.jwt.algorithms.Algorithm
    import io.ktor.auth.Principal
    import java.util.*
    
    object JwtConfig {
        private const val secret = "my-secret" // use your own secret
        private const val issuer = "com.imran"  // use your own issuer
        //private const val validityInMs = 10 // 1 day
        private const val validityInMs = 36_000_00 * 24 // 1 day
        private val algorithm = Algorithm.HMAC512(secret)
    
        val verifier: JWTVerifier = JWT
            .require(algorithm)
            .withIssuer(issuer)
            .build()
    
        /**
         * Produce a token for this combination of name and password
         */
        fun generateToken(JWTUser: JWTUser): String = JWT.create()
            .withSubject("Authentication")
            .withIssuer(issuer)
            .withClaim("name", JWTUser.name)
            .withClaim("password", JWTUser.password)
            .withExpiresAt(getExpiration())  // optional
            .sign(algorithm)
    
        /**
         * Calculate the expiration Date based on current time + the given validity
         */
        private fun getExpiration() = Date(System.currentTimeMillis() + validityInMs)
    
    }
    
    
    data class JWTUser(val name: String, val password: String, val other:String="default"): Principal
    And then how to use refresh token?
    j
    • 2
    • 6
  • a

    Alexander Finn

    10/02/2020, 1:15 PM
    Hey guys, one thing I’ve noticed since switched to ktor 1.4 (not sure if it was there before as well): when there is a (de)serialization problem during
    call.recieve
    or
    call.respond
    - it actually hides the exception and only prints something like this:
    INFO Application - 200 OK: GET - /api/v2/announcements, io failed
    In the case of deserialization exception during
    call.recieve
    it returns empty reponse with status 500, in the case of serialization durint
    call.respond
    it returns empty response with status 200 (and this is even more of a problem). Does it mean that the best practice is to always wrap both method calls with try..catch? Or any configuration option I can enable to make such issues more prominent in the logs and the ways responses are handled?
    r
    • 2
    • 7
  • h

    hdarritchon

    10/04/2020, 7:10 PM
    Hi, I am using #ktor server to produce an API in production. In this API, I have several endpoints. In a specific use case, one of my API endpoint is answering very slowly. In fact, I have put lots of measure inside my app and the time to respond from my API point of view is coherent. But from a customer point of view it could be ten times the time I have measured. I have reproduced the issue on my computer. I just have to use apache benchmark to stress a bit my app, as it is done in production, and the time of answering is going up very quickly. It looks like Ktor is being overwhelmed by the requests. I’d like to monitor the “queue” of request that Ktor has to manage ? Is there a way to do so ? Do you have any idea how I can track and find my issue ? Thanks.
    j
    • 2
    • 3
  • h

    hdarritchon

    10/05/2020, 7:04 AM
    Is it a good or a bad idea to modify the callGroupSize of Netty configuration ?
    /**
     * Specifies size of the event group for running application code
     */
    public var callGroupSize: Int = parallelism
    I’d like to increase this value.
    s
    m
    • 3
    • 3
  • n

    Nikolay Kasyanov

    10/05/2020, 7:25 AM
    Hey folks, just noticed this: https://github.com/ktorio/ktor/blob/aa1dd6a991ea0447aa30f0f791ef3099fe71031c/ktor-client/ktor-client-ios/darwin/src/io/ktor/client/engine/ios/certificates/CertificatePinner.kt#L231-L232 Is this reliable? 🤔
    🤔 1
    • 1
    • 1
  • h

    hdarritchon

    10/06/2020, 8:48 AM
    hi @Júlio Santos. What do you mean ?
    :thread-please: 1
    j
    • 2
    • 4
  • j

    Janez Kolar

    10/06/2020, 5:51 PM
    Hi all, I am quite new to backend and Ktor development, but look very interesting and easy to learn. Now I came to few questions. I have server based on Netty engine. Is it possible to hande 10k REST request per second. Server return json with cca list of 50 objects (like Person(name, surname, age, gender)). List is in memory cache. How and where should I configure Netty to achive high performance? I created:
    fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)
    val demo: Demo = Demo()
    val compute = newFixedThreadPoolContext(10, "compute")
    
    @Suppress("unused") // Referenced in application.conf
    @kotlin.jvm.JvmOverloads
    fun Application.module(testing: Boolean = false) {
    
         demo.generateflyingDemo()
    
        GlobalScope.launch(Dispatchers.Default) {
            while(isActive)
            {
                demo.demoMoving()
                delay(1000)
            }
        }
    
        install(Compression) {
            gzip {
                priority = 1.0
                minimumSize(256)
            }
            deflate {
                priority = 10.0
                minimumSize(1024) // condition
            }
        }
        install(CORS) {
            method(HttpMethod.Options)
            method(HttpMethod.Put)
            method(HttpMethod.Delete)
            method(HttpMethod.Patch)
            method(HttpMethod.Get)
    
            header(HttpHeaders.Authorization)
            header(HttpHeaders.Origin)
            header(HttpHeaders.XRequestId)
            allowCredentials = true
            anyHost() // @TODO: Don't do this in production if possible. Try to limit it.
        }
        install(WebSockets) {
            pingPeriod = Duration.ofSeconds(15)
            timeout = Duration.ofSeconds(15)
            maxFrameSize = Long.MAX_VALUE
            masking = false
        }
        install(Authentication) {
            basic("myBasicAuth") {
                realm = "Ktor Server"
                validate { if (it.name == "test" && it.password == "password") UserIdPrincipal(it.name) else null }
            }
        }
        install(ContentNegotiation) {
            gson {
            }
        }
    
        routing {
    
         
            get("rc/activePeople") {
    
                call.respondHandlingActivePeople()
            }
    
    
            get("/") {
                call.respondText("HELLO WORLD!", contentType = ContentType.Text.Plain)
            }
    
        }
    }
    
    
    private suspend fun ApplicationCall.respondHandlingActivePeople() {
       withContext(compute) {
            respond(demo.activePeople(age = 15))
        }
    }
    j
    • 2
    • 1
  • t

    Tobi

    10/07/2020, 1:23 PM
    Hey folks, I am working on converting a use-case in our Android App from retrofit/okhttp to ktor but according to this issue I am apparently using the wrong versions: https://github.com/Kotlin/kotlinx.serialization/issues/763 The error I am receiving:
    Caused by: java.lang.NoSuchMethodError: No direct method <init>(Ljava/lang/String;Lkotlinx/serialization/internal/GeneratedSerializer;I)V in class Lkotlinx/serialization/internal/SerialClassDescImpl; or its super classes (declaration of 'kotlinx.serialization.internal.SerialClassDescImpl
    The versions I am using:
    kotlin = 1.3.72
    org.jetbrains.kotlin.plugin.serialization = 1.3.72
    io.ktor:ktor-client-okhttp = 1.3.1
    io.ktor:ktor-client-serialization-jvm = 1.3.1
    io.ktor:ktor-client-logging-jvm = 1.3.1
    Which versions should I use for Kotlin
    1.3.72
    ? Can't change that one for now...
    • 1
    • 1
  • r

    rudolf.hladik

    10/07/2020, 2:27 PM
    Hello there, I have filled an issue (https://youtrack.jetbrains.com/issue/KTOR-1115) , is it the same issue as https://youtrack.jetbrains.com/issue/KTOR-499 or I do something wrong there?
    • 1
    • 1
  • j

    John O'Reilly

    10/07/2020, 5:06 PM
    Getting following when trying to stat Ktor server on Android 9...this seems to be Netty specific but if I try with Jetty instead it also crashes (but don't get any log like this). Same code works on Android 8.
    System.err: [main] INFO io.netty.util.internal.PlatformDependent - Your platform does not provide complete low-level API for accessing direct buffers reliably. Unless explicitly requested, heap buffer will always be preferred to avoid potential system instability.
    a
    m
    • 3
    • 6
  • j

    jorge.rego

    10/08/2020, 9:21 AM
    Hi all I’ve written an article in Medium about how to monitor Ktor API server with Prometheus & Grafana. I hope this can help you somehow. It took me a bit of time to integrate and build the dashboard I’ve shared, so it may save some of your time if you are looking for something similar. https://medium.com/@math21/how-to-monitor-a-ktor-server-using-grafana-bab54a9ac0dc
    👀 9
    r
    j
    • 3
    • 14
  • k

    KamilH

    10/09/2020, 6:57 AM
    I’m trying to run some tests on JVM/iOS/JS targets with
    MockEngine
    and it works on the JVM and JS targets, but fails on iOS with following message:
    kotlin.Error: Ktor native HttpClient requires kotlinx.coroutines version with `native-mt` suffix (like `1.3.9-native-mt`). Consider checking the dependencies.
    Where should I add those dependencies? I though I should add it in
    iosTest
    like that:
    sourceSets {
            val iosTest by getting {
                dependencies {
                    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.9-native-mt")
                }
            }
    }
    but it doesn’t help. Adding to
    iosMain
    also doesn’t change anything
    e
    t
    +2
    • 5
    • 17
  • m

    Marc Knaup

    10/09/2020, 10:24 PM
    Also, why is the OkHttp engine so slow? 2000k requests (max 200 in parallel) Apache: ~9s (standard config) Jetty: ~12s (standard config) OkHttp: ~15-36s (1k clients, 1k threads) I’d like to use Apache but it’s unusable (https://youtrack.jetbrains.com/issue/KTOR-717) Jetty also unstable (https://youtrack.jetbrains.com/issue/KTOR-1120) CIO also unstable (https://youtrack.jetbrains.com/issue/KTOR-1126) OkHttp is sloooow… (https://youtrack.jetbrains.com/issue/KTOR-1121)
    m
    g
    e
    • 4
    • 16
  • o

    Oleg Yukhnevich

    10/11/2020, 11:44 AM
    Is there some smart way to check, if there are no leaks while using ktor-io ByteReadPackets?
    • 1
    • 1
  • a

    aleksey.tomin

    10/12/2020, 7:53 AM
    How can I use
    kotlin.serialization
    in native (ktor client + curl)? Way from https://ktor.io/docs/serialization-converter.html
    install(ContentNegotiation) { serialization() }
    doesn’t work -
    ContentNegotiation
    exists only for jvm.
    j
    m
    g
    • 4
    • 6
  • m

    Marc Knaup

    10/12/2020, 10:42 AM
    How do I clean up resources after completing a call without closing the entire
    HttpClient
    ?
    HttpResponse.close()
    is deprecated. With CIO I get
    BindException: Can't assign requested address
    under high load which is probably due to some (temporary?) resource leak.
    e
    • 2
    • 5
  • e

    Elka

    10/12/2020, 1:47 PM
    Hello, I am trying to build a multi-platform client that retries the request automatically when the token expired and 401 is returned from the server. For that I am using a sample code by moko-network. The refresh token api is being triggered but when it retries the request using
    request
    , I never get a
    result
    as if some "deadlock" occurred.
    val requestBuilder = HttpRequestBuilder().takeFrom(context.request)
    val result: HttpResponse = context.client!!.request(requestBuilder)
    Any idea?
    👀 1
    n
    • 2
    • 3
  • t

    Trevor Ackerman

    10/12/2020, 2:47 PM
    What is the best way to start contributing to Ktor on gh?
    a
    • 2
    • 4
  • s

    Satyam Agarwal

    10/12/2020, 3:32 PM
    Hei, I am using
    HttpRequestBuilder
    block with
    url(completePath)
    and it is encoding my query string. How can I stop encoding of query string. For ktor http client jvm with CIO
    e
    j
    • 3
    • 3
  • p

    Peter Tran

    10/12/2020, 9:16 PM
    @e5l Question about this commit (8b6f074), why is CIO disabled for mingwX64? My current requirements include multiplatform, Windows, TLS, and OAuth2; I will try
    OkHttp
    .
    a
    e
    • 3
    • 3
  • s

    Shan

    10/13/2020, 12:55 AM
    Hey all. I'm seeking any form of documentation for how best to handle various error situations that can occur related to Websockets. The standard seems to be just "try and catch literally everything that could possibly be thrown on any engine", or to map specific exceptions for specific engines, but I was hoping that these situations might already be abstracted out to a common engine-agnostic exception/result that I haven't found anywhere? These are the two situations I really care about, though other more specific errors would be nice to handle as well: 1.) the device cannot host a http server because it does not have any sort of ethernet interface 2.) the device has an ethernet interface, but there's no connection available I can't seem to find in the source code (after some significant digging) where an exception can actually be thrown in either of those cases, or if it's even thrown at all. Any help would be appreciated 🙂 The end goal is to provide the user with as accurate of an error response as possible for what exactly went wrong.
    😞 1
    👀 1
    a
    l
    • 3
    • 3
  • r

    ribesg

    10/13/2020, 8:52 AM
    Looks like I’m the only user of Ktor on Kotlin/Native lol https://youtrack.jetbrains.com/issue/KTOR-1095 Or maybe I’m the only one who needs logs I don’t know
    👍 2
    t
    • 2
    • 2
  • r

    rsetkus

    10/13/2020, 10:28 AM
    Hi. Did anybody successfully implemented http cache-control on Ktor client? If yes, then I'll much appreciate if you could point me to any source (articles, documentation, code samples etc.) of implementation.
    m
    • 2
    • 11
  • b

    bitkid

    10/13/2020, 5:05 PM
    i found something weird. maybe anyone can help me? i start my ktor server with
    embeddedServer(Netty, environment = environment).start(true)
    do a curl on localhost:8080/version and it works (it returns some json) .. then i only change that line to
    embeddedServer(Jetty, environment = environment).start(true)
    hit the same URL and i get "curl: (52) Empty reply from server" any ideas?
    e
    • 2
    • 8
  • m

    MrPowerGamerBR

    10/14/2020, 1:56 AM
    Did anyone experience issues after upgrading to Ktor 1.4.1? After I upgraded to Ktor 1.4.1, after my application is up for a bit, my http client all my requests are timing out. This didn't happen in 1.3.1, now I'm downgrading to 1.3.1 to see if the issue persists or not, but still, this is very strange. It seems to be related to https://youtrack.jetbrains.com/issue/KTOR-717 but the issue seems to be present since 1.0.0 (!), so I'm not really sure if it is related.
    m
    • 2
    • 7
  • z

    zjuhasz

    10/14/2020, 3:16 AM
    Can a single ktor embedded server run more than one application simultaneously?
    • 1
    • 1
Powered by Linen
Title
z

zjuhasz

10/14/2020, 3:16 AM
Can a single ktor embedded server run more than one application simultaneously?
I noticed that subscribing to environment events passes an application to the callback function and I didn’t understand why if an environment can only run one application at a time.
View count: 2