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

    rocketraman

    12/18/2018, 6:27 PM
    I upgraded to ktor 1.0.1 and now consistently get
    java.util.concurrent.CancellationException: Channel has been cancelled
    from the ktor client, using CIO, with the same code that used to work with 1.0.0. Anyone else experienced this?
    e
    • 2
    • 7
  • m

    miha-x64

    12/18/2018, 7:06 PM
    Hello. [lazy mode] Is there a ready-to-use comments widget for ktor?
    s
    • 2
    • 6
  • d

    Dias

    12/19/2018, 10:38 AM
    Not really a ktor specific question, but it's in ktor context. We ported our service to ktor from servlet based framework, but we didn't touch any business code which contains blocking calls to db and other http services, do we just need to wrap those calls into
    withContext
    suspending calls to leverage coroutines better?
    💯 2
    🙏 1
    :yes: 2
    m
    • 2
    • 1
  • a

    Albert

    12/19/2018, 2:38 PM
    If I follow what is described there, then I am unable to find any instances of
    MockEngine
    e
    d
    • 3
    • 6
  • a

    Albert

    12/19/2018, 2:50 PM
    Related to the documentation, I can only create
    MockEngine
    like so
    MockEngine.invoke
    . Otherwise it keeps referencing to the constructor
    🤔 1
    e
    • 2
    • 2
  • o

    obobo

    12/19/2018, 2:58 PM
    Hello. I'm trying to use the ktor client, and in the samples I found the following call:
    val call = call {
            url(URL(url))
            method = HttpMethod.Get
    }
    Where is
    URL
    defined? IntelliJ is having a hard time finding it.
    e
    • 2
    • 10
  • a

    Alexander Potukar

    12/19/2018, 3:32 PM
    Hi everyone, Ktor is from what I understand a microframework and comparing it with Spring Boot is like mixing apples and oranges. Nonetheless I need some information for a framework shootout tomorrow in a project for one of our customers, and some of my colleagues including myself would appreciate using Kotlin with Ktor. I would like to know if "Exposed" is the preferred framework for DB access in the Ktor ecosystem. And are there any plans to provide some way to generate OpenAPI (Swagger) documentation based on the Routes used in Ktor? Thanx in advance...
    👍 1
    r
    l
    • 3
    • 7
  • a

    ahulyk

    12/20/2018, 9:40 AM
    I use ktor client + kotlin-native + kotlinx-serialization and i'm getting following error on ios side:
    io.ktor.client.call.ReceivePipelineException: Fail to run receive pipeline
    ext.kotlin_version = '1.3.10'
        ext.coroutines_version = '1.0.1'
        ext.ktor_version = '1.0.1'
        ext.serialization_version = '0.9.1'
    e
    s
    y
    • 4
    • 8
  • n

    NGupta

    12/20/2018, 1:08 PM
    I have proposed a change in the samples page: https://github.com/ktorio/ktorio.github.io/compare/master...nikhilgupta16:patch-1
    e
    o
    • 3
    • 2
  • r

    rrader

    12/21/2018, 8:18 AM
    Is there a module to auto generate swagger json, something like https://github.com/springfox/springfox ?
    s
    • 2
    • 1
  • g

    gotoOla

    12/21/2018, 12:12 PM
    Hi! I’ve seen a memory leak when we migrated from kotlin 1.2 with 0.x-coroutines and 0.9.5-ktor to kotlin 1.3, 1.0 coroutines and 1.0.1 ktor. I’ve been running a lot of memory profiling and narrowed it down ot our HttpClient. The memory leakage seems to be a lot of char[] . We have a class which acts as a http client. This class is called from another class with GlobalScope.launch {} (this was previously just launch) and is sending about 600 requests per second (but sometimes peaks at 1400 rps). With ktor 0.9.5 we had this working for a few months. I’m now looking for help since it’s not much code left that is in our control but maybe we have used it wrong. Anybody see something fishy in the code below or know about any known issue with the HttpClient? This is our httpClient which leaks memory.
    import our.company.toJsonString
    import our.company.ApplicationMetrics
    import io.ktor.client.HttpClient
    import io.ktor.client.engine.apache.Apache
    import io.ktor.client.engine.config
    import <http://io.ktor.client.request.post|io.ktor.client.request.post>
    import io.ktor.client.response.HttpResponse
    import org.slf4j.LoggerFactory
    
    class UpdateClient(
        baseUrl: String
    ) {
        private val logger = LoggerFactory.getLogger(UpdateClient::class.java)
        private val client = HttpClient(Apache.config {
            socketTimeout = 30_000
            connectTimeout = 30_000
        })
        private val updateUrl = "$baseUrl/shared"
    
        suspend fun postUpdates(updates: List<Update>) {
            try {
                val payload = updates.toJsonString()
                <http://client.post|client.post><HttpResponse>(updateUrl) {
                    body = payload
                }
                ApplicationMetrics.updatesSent.labels("true").inc(updates.size.toDouble())
            } catch (e: Exception) {
                logger.error("Could not post updates", e)
                ApplicationMetrics.updatesSent.labels("false").inc(updates.size.toDouble())
            }
        }
    }
    The service that calls this looks something like this
    fun businessLogic(urls: List<Url>) {
            runBlocking {
                val urlsInDynamo = urls.map { url ->
                    GlobalScope.async {
                        try {
                            val result = dynamoClient.increaseSharesAsync(url)
                            Update(result.attributes()["aString"]?.s()!!, result.attributes()["aValue"]?.n()!!.toLong())
                        } catch (e: Exception) {
                            logger.warn("Unable to write get result from the update to dynamo", e)
                            null
                        }
                    }
                }.awaitAll().filterNotNull()
    
                if (urlsInDynamo.isEmpty()) {
                    throw RuntimeException("Non of the urls were updated in Dynamo")
                }
    
                // Fire and forget
                GlobalScope.launch {
                    val updates = urlsInDynamo
                        .groupBy { it.aString }
                        .map {
                            it.value.maxBy {
                                it.value
                            }!!
                        }
                        .toList()
                    // This is where we call the update client at about 600 rps
                    updateClient.postUpdates(updates)
                }
            }
        }
    And the data class and extension we use
    fun Any.toJsonString(pretty: Boolean = false): String {
        return DefaultObjectMapper
            .let { if (pretty) it.writer(SerializationFeature.INDENT_OUTPUT) else it.writer() }
            .writeValueAsString(this)
    }
    data class Update(val aString: String, val aValue: Long)
    👀 1
    e
    a
    • 3
    • 20
  • a

    Alexandre

    12/23/2018, 6:37 PM
    I'm trying create my first code Kotlin using Ktor. I installed Jetty, and works ok. I useing this exemplo to create my first test: https://github.com/ktorio/ktor-samples/tree/master/deployment/jetty-war But when run gradlew I have ths error message:
    ./gradlew :teste:run
    
    FAILURE: Build failed with an exception.
    
    * What went wrong:
    Project 'teste' not found in root project 'teste'.
    
    * Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
    
    * Get more help at <https://help.gradle.org>
    
    BUILD FAILED in 0s
    This is my gradle file:
    buildscript {
        ext.gretty_version = '2.0.0'
        ext.kotlin_version = '1.3.11'
        ext.ktor_version = '1.0.1'
    
        repositories {
            mavenCentral()
            jcenter()
        }
        dependencies {
            classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
            classpath "org.akhikhl.gretty:gretty:$gretty_version"
        }
    }
    
    plugins {
        id 'java'
        id 'org.jetbrains.intellij' version '0.3.12'
        id 'org.jetbrains.kotlin.jvm' version '1.3.0'
    }
    
    apply plugin: 'kotlin'
    apply plugin: 'war'
    apply plugin: 'org.akhikhl.gretty'
    
    
    webAppDirName = 'webapp'
    
    gretty {
        contextPath = '/'
        logbackConfigFile = 'resources/logback.xml'
    }
    
    sourceSets {
        main.kotlin.srcDirs = [ 'src' ]
        main.resources.srcDirs = [ 'resources' ]
    }
    
    repositories {
        jcenter()
        maven { url "<https://kotlin.bintray.com/ktor>" }
    }
    
    dependencies {
        compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
        compile "io.ktor:ktor-server-servlet:$ktor_version"
        compile "io.ktor:ktor-html-builder:$ktor_version"
        compile "ch.qos.logback:logback-classic:1.2.3"
    }
    
    kotlin.experimental.coroutines = 'enable'
    
    task run
    
    afterEvaluate {
        run.dependsOn(tasks.findByName("appRun"))
    }
    where i'm worong?
    l
    • 2
    • 3
  • b

    bod

    12/23/2018, 7:52 PM
    currently I have one page, which shows a list of "available plugins" that each can be configured with a few fields, and the list of "currently configured plugins". The page uses a bit of CSS and Javascript.
    g
    • 2
    • 5
  • s

    savrov

    12/23/2018, 10:07 PM
    Guys, hello, Im using this framework to create auth2 server with ktor. But i dont understand how can i access methods for auth (Oauth2TokenService class, that i install as a feature) in my endpoints. https://github.com/myndocs/kotlin-oauth2-server Can someone look in it, please
    c
    • 2
    • 1
  • b

    bod

    12/24/2018, 12:00 AM
    Well, it's an epic fail, JTwig doesn't work either on Android...
    😒 1
    t
    • 2
    • 2
  • k

    kenkyee

    12/24/2018, 12:25 PM
    Or just generate the HTML yourself. One page? Sounds like a lot of work for something trivial...
    b
    g
    • 3
    • 10
  • b

    bod

    12/24/2018, 3:57 PM
    I'm gonna try this one first: https://github.com/fizzed/rocker 😂 (yes I really really don't want to have this html page in the middle of my code)
    g
    • 2
    • 2
  • s

    spierce7

    12/24/2018, 9:11 PM
    is there an example of deserializing a requests body?
    c
    • 2
    • 2
  • s

    spierce7

    12/24/2018, 9:23 PM
    I just tried upgrading to ktor 1.1.0. I can no longer call
    install(Authentication) {
    in the context of
    Application
    . How should I be doing this now?
    ➕ 1
    c
    d
    e
    • 4
    • 11
  • j

    Jonas Bark

    12/24/2018, 10:41 PM
    Getting Program type already present: org.slf4j.impl.StaticMDCBinder when trying to compile an android app with 1.1.0 I'm using implementation "io.ktor:ktor-client-core-jvm:$ktor_version" implementation "io.ktor:ktor-client-json-jvm:$ktor_version" implementation "io.ktor:ktor-client-logging-jvm:$ktor_version" implementation "io.ktor:ktor-client-okhttp:$ktor_version" on the JVM side. Maybe because logging-jvm uses an older version of slf4j-simple which has a dependency on a different org.slf4j😒lf4j-api:1.6.1 version than all the other libraries?
    • 1
    • 1
  • j

    Jonas Bark

    12/24/2018, 11:11 PM
    Can't compile 1.1.0 for iOS - can it be a case sensitivity issue? Using presets.iosX64 (for simulator) it wouldn't compile due to this error:
    Could not resolve all files for configuration ':common:iosCompileKlibraries'.
    > Could not find io.ktor:ktor-http-iosx64:1.1.0.
    It searches for this URL: https://dl.bintray.com/kotlin/ktor/io/ktor/ktor-http-iosx64/1.1.0/ktor-http-iosx64-1.1.0.module which results in a 404 error, while the one with X64 instead of x64 does exist https://dl.bintray.com/kotlin/ktor/io/ktor/ktor-http-iosX64/1.1.0/ktor-http-iosX64-1.1.0.module
    👀 1
    • 1
    • 1
  • b

    bod

    12/25/2018, 11:15 AM
    Hello, World! And Merry Xmas 🙂 I'm trying the kotlinx.html integration now. Is there a way to add custom attributes to a tag? In my case, I need to add a
    defer
    attribute to a
    script
    tag.
    o
    • 2
    • 2
  • s

    savrov

    12/25/2018, 12:32 PM
    for some of my request sometimes I receive a fatal error: io.ktor.features.UnsupportedMediaTypeException: Content type / is not supported. I tried to wrap a request receiver method in try-catch block, but it happens somewhere early. Ktor version 1.0.0
    t
    • 2
    • 5
  • l

    Lucas

    12/25/2018, 9:10 PM
    Could someone take a look at this WebSocket test case? The function
    handleWebSocketConversation
    blocks the execution forever, so the test does not finish.
    t
    • 2
    • 8
  • b

    bitkid

    12/26/2018, 9:46 AM
    where did HttpStatusCode go?
    e
    d
    • 3
    • 8
  • r

    russhwolf

    12/26/2018, 11:57 PM
    Are ios artifacts now published separately per architecture? I can’t resolve
    io.ktor:ktor-client-core-ios:1.1.1
    ,
    io.ktor:ktor-client-json-ios:1.1.1
    , or
    io.ktor:ktor-client-mock-ios:1.1.1
    , but using
    iosx64
    instead of
    ios
    works fine. Oddly I have no issue with
    io.ktor:ktor-client-ios:1.1.1
    .
    j
    e
    • 3
    • 4
  • r

    russhwolf

    12/27/2018, 1:58 AM
    Some questions: 1. There’s a bunch of
    META-INF
    files which were giving me build issues until I added this line: https://github.com/russhwolf/ktor-demo/blob/master/app/build.gradle#L27. I know I’ve seen other such issues in the past and they’ve been fixed. Is this a known issue currently? 2. Is the strategy I’m using to dynamically switch between x64 and arm64 dependencies sane? Also is it necessary, or did I miss something?
    :yes: 1
    e
    • 2
    • 1
  • h

    hates

    12/27/2018, 9:58 AM
    Coming Ruby Rails where I can use the
    dotenv
    gem to store environment variables in a
    .env
    file then override them on the server with proper env variables, is there a good alternative for Kotlin/Ktor? Or a standard way of achieving the same thing?
    e
    • 2
    • 1
  • d

    deviant

    12/27/2018, 12:07 PM
    Reduced JDK7/8 dependencies
    does it mean you guys are moving in multiplatform direction?
    :yes: 2
    🎉 4
    n
    • 2
    • 1
  • a

    Ameho Chan

    12/27/2018, 12:12 PM
    Could ktor be deployed on jboss by packing it into a war file. I add a web.xml by following the document. It works on my local machine but failed on the remote test environment.
    ✅ 1
    c
    • 2
    • 17
Powered by Linen
Title
a

Ameho Chan

12/27/2018, 12:12 PM
Could ktor be deployed on jboss by packing it into a war file. I add a web.xml by following the document. It works on my local machine but failed on the remote test environment.
✅ 1
c

cy

12/27/2018, 12:25 PM
Do you deploy it into root context path? How exactly it is not working?
a

Ameho Chan

12/27/2018, 12:35 PM
Yeah, I deployed the war into root context path. I use guice to init and load the ktor application. The deployment on jboss don't do anything after the jboss started until I request the index page from browser.
The log
Successfully started the ctuom admin.
didn't print after the jboss starting. When I request the index url on browser. A bunch of bootstrap log printed and finally the
Successfully started the ctuom admin.
showed.
c

cy

12/27/2018, 12:48 PM
So, do you get 404 or something?
or a blank page?
a

Ameho Chan

12/27/2018, 12:52 PM
Nope. The main problem is that the ktor application in war don't fully start on jboss unless request any url of the ktor application.
c

cy

12/27/2018, 12:58 PM
Why do you think that it's not correct? It is done as designed and is controlled by by load-on-startup web.xml parameter
In the
<servlet>
section with
ServletApplicationEngine
you can specify
<load-on-startup>1</load-on-startup>
👍 1
Otherwise it is lazily initialized by a servlet container
a

Ameho Chan

12/27/2018, 1:01 PM
Tks, this fixed my problems. 😁
👍🏻 1
c

cy

12/27/2018, 1:03 PM
I believe you are the first one who tried to deploy it into JBoss container. Please let us know is something doesn't work
😅 1
btw, is it old JBoss or Wildfly?
a

Ameho Chan

12/27/2018, 1:05 PM
Wildfly 8
c

cy

12/27/2018, 1:06 PM
our integrations tests are running inside of Tomcat, Perhaps we can configure it for wildfly one day
a

Ameho Chan

12/27/2018, 1:09 PM
I hope so. Besides servlet 3.0 don't require the
web.xml
. Could we have a
ServletInitializer
like spring boot.
c

cy

12/27/2018, 1:11 PM
Ok, I did create https://github.com/ktorio/ktor/issues/836
a

Ameho Chan

12/27/2018, 1:15 PM
That's cool. Thanks for your help.
View count: 4