https://kotlinlang.org logo
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
  • d

    Dragos Rachieru

    01/07/2021, 11:36 AM
    Do websockets work in 1.5.0? I am sending a Frame, but the client is not receiving it.
    c
    • 2
    • 8
  • i

    igor.wojda

    01/07/2021, 12:47 PM
    I have enabled
    development = true
    in the
    application.conf
    file and I can see stack-traces in the console. Now I wonder is there any way to print into console all requests and responses (including returned data like JSON and http codes) ?
    d
    • 2
    • 3
  • a

    Arkangel

    01/07/2021, 3:17 PM
    Hi guys ..has anyone found a way to build an authentication feature that wraps around firebase on ktor
    j
    l
    • 3
    • 14
  • m

    MrPowerGamerBR

    01/09/2021, 10:32 PM
    Hello everyone! It seems that the docs has some issues that I found: 1. The routing path parameters documentation is missing (Example: How Ktor demonstrates how
    /test/{param}
    works, stuff like that, here: https://web.archive.org/web/20200611221212/https://ktor.io/servers/features/routing.html) 2. The AutoHeadResponse docs requires a dependecy that doesn't exist, but AutoHeadResponse is automatically included in Ktor! I would've reported this in the correct location, but I can't find the repository that has Ktor's docs! (Only the API stuff seems to be in a repository, not the docs themselves) Thank you 🙂
    d
    h
    • 3
    • 2
  • i

    igor.wojda

    01/11/2021, 10:23 AM
    How to run Ktor application from cmd?
    b
    a
    • 3
    • 2
  • d

    Dariusz Kuc

    01/12/2021, 8:35 PM
    hello 👋 are there any migration guides from 1.3.x -> 1.4/1.5? looks like some of the artifacts got renamed and no longer resolve
    c
    a
    j
    • 4
    • 22
  • i

    Ifvwm

    01/14/2021, 5:52 AM
    why take a HttpResponse from a download link would take a long time?
    val client = HttpClient(CIO) {
            followRedirects = false
        }
            val _result = client.get<HttpResponse>(addr)
            val readInputStream = client.get<InputStream>(_result.headers["LOCATION"]?:"")
    //        val count = client.get<HttpResponse>(_result.headers["LOCATION"]?:"")
    the comment line would take 20 seconds
    g
    r
    • 3
    • 2
  • i

    Ifvwm

    01/14/2021, 6:07 AM
    httpClient.put<ByteArray>(realUrl){
                body = "aha".toByteArray()
            }
    this code can upload data to a link, now I need to get upload progress, how to use a outputStream to instead of this way to upload data?
    val _outputStream = httpClient.put<HttpResponse>(realUrl)
            val outputStream = _outputStream.receive<OutputStream>()
    
            outputStream.write("abc".toByteArray())
            outputStream.flush()
            outputStream.close()
    this won't work, error message o.ktor.client.call.NoTransformationFoundException: No transformation found: class io.ktor.utils.io.ByteBufferChannel (Kotlin reflection is not available) -> class java.io.OutputStream (Kotlin reflection is not available)
    g
    • 2
    • 4
  • a

    Alexandre Brown

    01/15/2021, 5:28 AM
    1 : Does Ktor plan on adding GraalVM to their official doc like they greatly did with Docker? 2 : What is the current support for Ktor + GraalVM (native image) ? Do you guys know where I can find more up-to-date resources to get started? I couldn't get a hello world to work last time. Or do you guys know any other solution to address the deployment size (JVM-related concern).
    b
    • 2
    • 1
  • i

    Ifvwm

    01/15/2021, 9:10 AM
    val outputStream = httpClient.put<ByteWriteChannel>(realUrl).toOutputStream()
            outputStream.write("abc".toByteArray())
            outputStream.flush()
            outputStream.close()
    why this won't put data to that link? but with httpurlconnection is ok
    r
    • 2
    • 3
  • m

    malinskiy

    01/15/2021, 10:42 AM
    Hey guys, can someone explain to me how the proper closing of sockets in ktor should look like? I have something like:
    override suspend fun <T> openConnection(socketAddress: InetSocketAddress, block: suspend (Socket) -> T): T {
        val socketJob = Job()
        var selectorManager: SelectorManager? = null
        var socket: Socket? = null
        try {
            selectorManager = ActorSelectorManager(socketJob + coroutineContext)
            socket = aSocket(selectorManager)
                .tcp()
                .connect(socketAddress) {
                    socketTimeout = 10_000
                }
            return block(socket)
        } finally {
            withContext(NonCancellable) {
                selectorManager?.close()
                socket?.close()
                socketJob?.complete()
            }
        }
    }
    The channels opened in block() are closed in all cases. What I’m observing (attached the screenshots) is that shutdownOutput() is sent, so the client socket gets into the FIN_WAIT_1, but there is no way for me AFAIK to wait for the whole 4-way TCP close to properly finish, so I end up with server socket that is still open and doesn’t know the client is dead. Sometimes the server sockets ends up in the CLOSE_WAIT as well. I’ve checked the timeout tests in https://github.com/ktorio/ktor/blob/master/ktor-client/ktor-client-java/jvm/test/io/ktor/client/engine/java/RequestTests.kt#L52 and if you place a breakpoint after
    runBlocking
    , I’m seeing the same socket behaviour. Is it something that I’m missing or there is a problem in ktor? 🙂 thanks
    • 1
    • 1
  • h

    Helio

    01/15/2021, 11:06 PM
    Hello Ktor team! I was hoping I could get your attention in this post, please. I wonder if you could shed some light on whats going on. https://kotlinlang.slack.com/archives/C9EJFT6DB/p1610747171006700?thread_ts=1610747171.006700&amp;cid=C9EJFT6DB
    • 1
    • 2
  • c

    crummy

    01/16/2021, 9:40 PM
    Is it possible to implement an interface to describe my routing in Ktor? (I'd like to share e.g. a UserApi interface between my frontend and backend.)
    c
    • 2
    • 4
  • d

    Damien

    01/17/2021, 8:07 PM
    Hi, I am using kotlinx.serialization ContentNegotiation and my response have the following hierarchy:
    sealed class A () 
    data class B(val name) : A()
    data class C(val name): A()
    My endpoint returns a List<A> and according to https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md#sealed-classes I would expect the following format:
    [
      {
    	"type": "com.A",
    	"name": "name"
      }
    ]
    And I am getting this format when Log the response object. Unfortunately, I got another response format when calling the endpoint:
    [
      [
    	"com.A",
    	{
    	  "name": "name"
    	}
      ]
    ]
    Any ideas why this different format appears when responding with call.respond(object)?
    i
    • 2
    • 3
  • s

    spierce7

    01/18/2021, 9:32 PM
    Does ktor have a common exception that it throws for io exceptions, like request timeouts, or networking issues?
    e
    • 2
    • 1
  • j

    Jose A.

    01/19/2021, 10:12 AM
    After upgrading to 1.5.0 (from 1.4.3) I got this error:
    Caused by: kotlinx.serialization.SerializationException: Class 'ArrayList' is not registered for polymorphic serialization in the scope of 'Collection'.
    Partial stacktrace:
    kotlinx.serialization.SerializationException: Class 'ArrayList' is not registered for polymorphic serialization in the scope of 'Collection'.
    Mark the base class as 'sealed' or register the serializer explicitly.
    	at kotlinx.serialization.internal.AbstractPolymorphicSerializerKt.throwSubtypeNotRegistered(AbstractPolymorphicSerializer.kt:103)
    	at kotlinx.serialization.internal.AbstractPolymorphicSerializerKt.throwSubtypeNotRegistered(AbstractPolymorphicSerializer.kt:113)
    	at kotlinx.serialization.PolymorphicSerializerKt.findPolymorphicSerializer(PolymorphicSerializer.kt:96)
    	at kotlinx.serialization.internal.AbstractPolymorphicSerializer.serialize(AbstractPolymorphicSerializer.kt:32)
    	at kotlinx.serialization.json.internal.StreamingJsonEncoder.encodeSerializableValue(StreamingJsonEncoder.kt:223)
    	at kotlinx.serialization.json.Json.encodeToString(Json.kt:73)
    	at io.ktor.serialization.SerializationConverter.convertForSend(SerializationConverter.kt:118)
    	at io.ktor.features.ContentNegotiation$Feature$install$2.invokeSuspend(ContentNegotiation.kt:146)
    	at io.ktor.features.ContentNegotiation$Feature$install$2.invoke(ContentNegotiation.kt)
    e
    r
    j
    • 4
    • 14
  • a

    andylamax

    01/19/2021, 11:07 AM
    Hello, Hope you are all okay. If you can please take some time and help me figure out what I am doing wrong. So, I have this
    install(CORS) {
        method(HttpMethod.Options)
        method(HttpMethod.Patch)
        method(HttpMethod.Delete)
        header(HttpHeaders.XForwardedProto)
        anyHost()
        header(AccessControlAllowOrigin)
        header(AccessControlAllowMethods)
        header(AccessControlAllowCredentials)
        header(AccessControlAllowHeaders)
        header(AccessControlRequestMethod)
        header(AccessControlRequestHeaders)
        header(AccessControlExposeHeaders)
        header(AccessControlMaxAge)
    
        allowCredentials = true
        maxAgeInSeconds = 1000
        allowNonSimpleContentTypes = true
    }
    But I still get this, when I run on the browser. What am I doing wrong? All I need is this request to work
    Access to fetch at '<http://192.168.43.218:9010/v1/authorization/user-roles/all>' from origin '<http://localhost:8080>' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
    Currently on: ktor 1.4.3 Kotlin: 1.4.21
    j
    • 2
    • 11
  • t

    tylerwilson

    01/19/2021, 4:07 PM
    How should we handle youtrack issues that are marked fixed, but that we have more comments or concerns about? Should I make a new issue and reference the original? Here is the one I am referring to specifically: https://youtrack.jetbrains.com/issue/KTOR-455
    r
    • 2
    • 2
  • s

    spierce7

    01/19/2021, 10:32 PM
    Is there a way I can check the md5 checksum for a file I downloaded with ktor?
    m
    • 2
    • 7
  • t

    than_

    01/20/2021, 11:26 AM
    hi, is there a way to attach interceptor after
    call.respond
    is called? Lets say I want to log something on calls with specific status codes.
    j
    • 2
    • 2
  • j

    Júlio Santos

    01/20/2021, 12:25 PM
    Hello guys! I'm trying to use
    Server-Sent Events
    with
    Ktor
    , does anyone have an example? Because I didn't find anything enlightening. I can send the event, but I can't consume it.
    a
    • 2
    • 2
  • k

    Kuba Petržílka

    01/20/2021, 2:50 PM
    Hello everyone! We are about to build some new applications in our company to support external APIs. The first of them should be quite small and I was trying to convince people to use Ktor for it. We are already using Kotlin as a primary language even in our big monolithic app so I kind of sense that it would be better to use something more natural to Kotlin. I've been told that Ktor is a cool thing but not suitable for company like us, because people would have to have some initial knowledge about it and because Ktor is very small and lacks things like CDI so there are some strong opinions that we should stick with Spring Boot mainly because of our developer base. But I don't like Spring and the annotation-driven programming and all the magic.. Would you help me to collect some good arguments for using Ktor (+Exposed) instead of SpringBoot (+Hibernate)? I really think we have good oportunity for our devs to get in touch with it, but I need to convince them.. 😄
    ➕ 4
    a
    m
    +4
    • 7
    • 13
  • s

    spand

    01/22/2021, 11:23 AM
    We use basic auth but after installing a StatusPages handler for HttpStatusCode.Unauthorized I no longer get a challenge when accessing the protected urls. Any hints for fixing this ? Maybe its a bug ?
    j
    • 2
    • 1
  • s

    Sebastian Kaspari

    01/22/2021, 6:39 PM
    If I’d write a custom
    HttpClientEngine
    , is there any way I can run the ktor test suite on them? Those tests do not happen to get published to maven, or? There’s
    ktor-client-tests*
    but it doesn’t contain the actual test cases, right?
    c
    • 2
    • 3
  • s

    Sam

    01/22/2021, 10:08 PM
    Is it possible to secure an api endpoint using OAuth and Ktor? I’m trying to use Postman to call my endpoint but Kto keeps trying to redirect to my OAuth server to request a token. I have the Bearer token setup in Postman and it is sending it along in the POST request. Setup details in thread ->
    • 1
    • 1
  • r

    rsktash

    01/23/2021, 8:33 AM
    Hi. I’m having issue when send multipart data SerializationException: Serializer for class ‘MultiPartFormDataContent’ is not found
    l
    • 2
    • 1
  • p

    Poohrang

    01/23/2021, 5:12 PM
    I have a simple question. Can I execute ktor server without IntelliJ IDE?
    :yes: 5
    m
    • 2
    • 2
  • j

    Joost Klitsie

    01/24/2021, 9:43 AM
    Hey guys! I have a ktor backend and I put all my different routes into packages that should not depend that much on each other. Therefore i was thinking, why don't i experiment with microservices! Does anyone have any good articles on that topic? How to setup a system, which tools to use, anything in that direction would be helpful :) i now mostly find articles about ktor itself (with for some reason microservice in the title) and not much about how to deploy n-amount of services with routing to all of them.
    👍 1
    k
    • 2
    • 2
  • s

    Satyam Agarwal

    01/24/2021, 7:30 PM
    Hei. I am trying to use Ktor CIO client to make request to server that uses TLSv1.2 with
    ECDHE-RSA-AES256-GCM-SHA384
    as cipher suite. But I get http handshake failure, if I use Apache as engine it works. I thought this was fixed here : https://github.com/ktorio/ktor/issues/439 Can someone help me please ?
    • 1
    • 3
  • s

    spierce7

    01/25/2021, 3:21 AM
    I’m trying to download a file directly to disk with ktor. I’m using the ktor streaming api, but I’m still seeing my memory on device go from 64MB to 200+MB (about the size of the file) while the large file is downloading. What am I doing wrong? Code in thread.
    c
    • 2
    • 3
Powered by Linen
Title
s

spierce7

01/25/2021, 3:21 AM
I’m trying to download a file directly to disk with ktor. I’m using the ktor streaming api, but I’m still seeing my memory on device go from 64MB to 200+MB (about the size of the file) while the large file is downloading. What am I doing wrong? Code in thread.
suspend fun downloadVideo(
    httpClient: HttpClient,
    url: String,
    to: File,
): Flow<Float> = flow {
    emit(0f)
    val response = httpClient.get<HttpStatement>(url).execute()

    val fileWriter = to.outputStream()
    val bytes = response.receive<ByteReadChannel>()

    try {
        val byteBufferSize = 1024 * 100
        val byteBuffer = ByteArray(byteBufferSize)
        val contentLength = response.contentLength()
        var totalRead = 0

        do {
            val currentRead = bytes.readAvailable(byteBuffer, 0, byteBufferSize)

            if (currentRead > 0) {
                totalRead += currentRead

                if (contentLength != null) {
                    val progressPercent = totalRead / contentLength.toFloat()
                    val floorProgressPercent = (progressPercent * 100).toInt() / 100f
                    emit(floorProgressPercent)
                }

                fileWriter.write(byteBuffer, 0, currentRead)
            }
        } while (currentRead >= 0)

    } finally {
        fileWriter.flush()
        fileWriter.close()
    }

    emit(100f)
}.flowOn(<http://Dispatchers.IO|Dispatchers.IO>)
c

cy

01/25/2021, 8:01 AM
You should use execute with block inatead otherwise it reads thre whole content
s

spierce7

01/25/2021, 3:14 PM
Really? Why? That’s extremely non-obvious
View count: 4