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

    Rescribet

    08/02/2021, 7:55 AM
    Is there a reason why
    io.ktor.http.URL
    isn’t
    @Serializable
    ? Seems like a good way to avoid

    primitive obsession▾

    and a quick win to get basic validation:
    @Serializable
    data class Person(
        val name: String,
        val friends: String,
    )
    val p = Person("Abbey", "<http://ex.com/abbey/friends>")
    Json.encodeToString(p) // { "name": "Abbey", "friends": "<http://ex.com/abbey/friends>" }
    
    val err = """
    	{ "name": "Abbey", "friends": "abbey/friends" }
    """
    Json.decodeFromString<Person>(err) // MalformedUrlException : SerializationException
    d
    • 2
    • 5
  • j

    jean

    08/03/2021, 8:41 AM
    I’m having configuration issue with
    application.conf
    , I declared the following :
    ktor {
        deployment {
            port = 8080
            port = ${?PORT}
        }
        application {
            modules = [ ... ]
        }
        jwt {
            secret = "secret"
            issuer = "<http://0.0.0.0:8080/>"
            audience = "<http://0.0.0.0:8080/login>"
            realm = "Access to 'login'"
        }
        pbkdf2 {
            salt = "salt"
            iterations = "10000"
            keyLength = "512"
        }
    }
    when I use
    environment.config.property("jwt.secret").getString()
    from
    Application.kt
    I receive this error
    Caused by: io.ktor.config.ApplicationConfigurationException: Property jwt.secret not found.
    What am I doing wrong here?
    d
    • 2
    • 2
  • c

    coder82

    08/03/2021, 2:02 PM
    I am sending a get request with username and password for basic authentication in the url, unfortunately the password contains $ sign, how do I disable the url encoding? I cannot send the a password with a $ as it turns into %24, pls help.
    h
    a
    • 3
    • 5
  • j

    Jgafner

    08/03/2021, 2:45 PM
    Hi Is there a way to override an install Plugin (formerly known as Features 🙂 ) in the tests ? More specifically I would like to override Koin installation Thanks
    a
    • 2
    • 4
  • v

    Václav Beneš

    08/03/2021, 9:00 PM
    Hi I d like to add ssl certificates to ktor client. Is it possible add them to default engine or should i use okhttps. Does ktor load ssl from system ? Thx
    a
    • 2
    • 4
  • d

    Danish Ansari

    08/04/2021, 5:50 AM
    Hi, I would like to receive
    List<Stirng>
    in a
    GET
    request what's the most efficient way to do so? I'm currently doing like this but was hoping if I can receive List<String> without any manual operation
    val keywords = call.request.queryParameters["keywords"]?.split(',') // List<String>?
    GET
    url will be like
    ?keywords=a,b,c
    ł
    b
    m
    • 4
    • 16
  • a

    Ali Khaleqi Yekta

    08/04/2021, 11:53 AM
    Hi. Is there a way to measure the transferred size of a static file at the end of the request? For example, we have a 2GB static file. A user requests to get the file but cancels it when it's 25% completed. How to get the size which is 512MB?
    a
    • 2
    • 1
  • b

    borisdamato

    08/04/2021, 2:42 PM
    👋 I’m using the Auth client plugin with Bearer provider, is there a way to prevent ktor for making multiple refresh token requests at once? For context, if my app makes 2 concurrent requests and they both fail due to expired access token, ktor at the moment makes 2 token refresh requests, one of which fails as the refresh token it used was already consumed by the first token refresh call. Ideally I’d want ktor to only ever execute one token refresh and then retry both original requests
    • 1
    • 1
  • j

    Jgafner

    08/04/2021, 5:51 PM
    Hi Is it possible to declare a list of Json objects in the config file and read it with the config.property? we have something like this:
    key : [
    {
      aKey: aValue
    },
    {
      bKey: bValue
    }
    ]
    ....
    IJ suggesting me one of those but I am not sure which one to use
    a
    c
    • 3
    • 11
  • j

    Jeff

    08/05/2021, 5:17 AM
    Hey. Has anyone handled continuous delivery using ktor and kubernetes/docker. I really need a sample. Feel like it will save me a lot of time in the long run.
    👀 1
    ł
    a
    c
    • 4
    • 3
  • j

    jozefdransfield

    08/06/2021, 8:40 AM
    Hi all im trying to track down an issue with a long running websocket connection using ktor client, i send one message at the start and then im just receiving messages, in the past i have seen that the connection can get dropped, but i only get an error message when i try and send something, does anyone know if there is a way to check the connection periodically without writing something to the stream?
    o
    • 2
    • 2
  • f

    Fernando Avanzo

    08/06/2021, 2:01 PM
    Hi fellows, i am work with ktor and netty as server, and after run a load test we discover that the aplication is losting requests, we realized that the configuration parameter the Netty is not otimized. I would ask if you guys can help me figuring out how to optimize netty settings in ktor. Thanks a lot for the help
    m
    • 2
    • 1
  • h

    Hadi

    08/07/2021, 8:29 AM
    Hello all, I am trying to use a function to create the HTML for my response in Ktor using the following:
    route("{year}") {
        get {
            val year = call.parameters["year"]!!.toIntOrNull()
            if (year == null) {
                call.respondText { "Year can only be an integer" }
            } else {
                val posts = PostRepo.getByDate(year)
                call.respondHtml { respondWithPostList(posts) }
           }
        }
    }
    
    fun respondWithPostList(posts: List<PostDTO>?) {
        HtmlContent {
            head { title { +"Posts" } }
            body {
                posts?.forEach { post ->
                    run {
                        div {
                            h3 {+"${post.title} (${post.id})"}
                            p {+post.author.email}
                        }
                    }
                }
            }
        }
    }
    But it does not work. However, the following works:
    route("{year}") {
        get {
            val year = call.parameters["year"]!!.toIntOrNull()
            if (year == null) {
                call.respondText { "Year can only be an integer" }
            } else {
                val posts = PostRepo.getByDate(year)
                call.respondHtml {
                    head { title { +"Posts" } }
                    body {
                        posts?.forEach { post ->
                           run {
                                div {
                                    h3 {
                                        +"${post.title} (${post.id})"
                                    }
                                    p {
                                        +post.author.email
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    Does anyone know what I do wrong? what is the correct way to produce HTML in a function?
    a
    • 2
    • 1
  • g

    Gerard de Leeuw

    08/07/2021, 1:09 PM
    HtmlContent {
            head { title { +"Posts" } }
    }
    Here you are effectively calling the constructor of HtmlContent and adding content to it, but you are not returning the constructed instance. Your function
    respondWithPostList
    has no return type, so it will implicitly return
    Unit
    . I think the most neat solution is to make your
    respondWithPostList
    function an extension method of
    HtmlContent
    . So it would look like this:
    fun HtmlContent.respondWithPostList(posts: List<PostDTO>?) {
            head { title { +"Posts" } }
            body {
                posts?.forEach { post ->
                    run {
                        div {
                            h3 {+"${post.title} (${post.id})"}
                            p {+post.author.email}
                        }
                    }
                }
            }
    }
    h
    • 2
    • 4
  • o

    okarakose

    08/07/2021, 6:31 PM
    Hello everyone, I want to start ktor project with Intellij Idea CE. I need to install ktor plugin inside IDE but marketplace only shows "obsolete" plugin. I downloaded latest version from website and try to "Install Plugin from Disk" option but it gives this error. I researched and found new ktor plugin is only support Intellij Idea "Ultimate" version and it disappointed me. I can't afford to buy Ultimate version. Should I use ktor only if I have Ultimate version, right?
    h
    h
    • 3
    • 2
  • j

    Jonathan Hollingsworth

    08/08/2021, 12:14 AM
    Hello everyone. I'm a total Kotlin, and Java, noob so if my question is embarrassing, I'm sorry. But... I started a new Ktor project and included routing and compression plugins. I wanted to be able to serialize my models for output in my routes, so following the pattern in https://ktor.io/docs/creating-http-apis.html#dependencies I added the serialization plugin (https://plugins.gradle.org/plugin/org.jetbrains.kotlin.plugin.serialization) to the
    build.gradle.kts
    file. When I do that, the
    ./gradlew build
    goes from passing, to failing with
    Could not determine the dependencies of task ':distTar'.
    > Could not resolve all dependencies for configuration ':runtimeClasspath'.
       > Could not create task ':compileKotlin'.
          > Could not create task of type 'KotlinCompile'.
             > Could not create an instance of type org.jetbrains.kotlin.gradle.tasks.KotlinJavaToolchainProvider.
                > Could not generate a decorated class for type KotlinJavaToolchainProvider.
                   > Cannot have abstract method KotlinJavaToolchain.getJdk().
    Totally flummoxed me, and my google-fu has failed me. Can anyone point me in the right direction please?
    a
    • 2
    • 8
  • h

    Hadi

    08/08/2021, 8:08 AM
    Hello all, I could not find anything on the absolute path in Ktor routing on the internet. Do you know a way one can link to a path generated form absolute top level of the app? e.g.
    route("") {
        route("/{year}/{month?}/{day?}") {
            get {
                call.respondHtml{
                    title { +"title" }
                    body {
                        a (href = "$baseUrl/somepath") { +"link to top level" }
                    }
                }
            }
        }
    }
    In this example, if I do
    href="/somepath"
    , it will go to different places if month or day is given.
    a
    • 2
    • 5
  • j

    jmfayard

    08/08/2021, 5:40 PM
    What are you using to do GraphQL with ktor?
    b
    j
    • 3
    • 5
  • r

    Rafs

    08/08/2021, 8:59 PM
    Is there any ORM for ktor?
    d
    a
    ł
    • 4
    • 3
  • j

    jeff

    08/09/2021, 1:26 AM
    I'm using the IntelliJ wizard for kotlin "full stack web application" -- I'm wondering if there's any way to split the kotlin/js part of the code depending on the route. Right now it seems to bundle it all into
    /static/myproject.js
    with no way to be more granular?
    t
    • 2
    • 1
  • m

    Matthieu Stombellini

    08/09/2021, 10:52 AM
    Hello! I'm trying to implement a feature that sends a HTTP 301 redirection when certain paths are requested, but nothing has matched them in the routing step (note that I'm building general-purpose redirection feature, so just putting those paths directly in the
    routing {}
    block is not an option). It seems that intercepting the
    Fallback
    pipeline would be a good solution, but it turns out that a response is already sent earlier in that pipeline by default due to this code: https://github.com/ktorio/ktor/blob/066d0c4f12debb32b3e7385ca07c4f1bd767e0a4/ktor-[…]t-common/jvm/src/io/ktor/server/engine/BaseApplicationEngine.kt, thus triggering a ResponseAlreadySentException when I try to call
    call.respond(...)
    in my interceptor. Is there anyway to intercept the pipeline before the default interceptors kick in, or if not, which phase should I intercept?
    a
    • 2
    • 2
  • p

    Piotr Krzemiński

    08/09/2021, 12:04 PM
    Hi! I'm running a server using CIO engine and I'm getting HTTP 403 when trying to call a PATCH endpoint that uploads a photo. It doesn't even enter the handler logic, just returns 403 without any details. I stumbled upon URLConnection works fine but ktor client returns 403 forbidden during a get request : KTOR-309 but it's about CIO in client engine. It works locally and I see HTTP/1.1 is used, but it doesn't work when I deploy it to AWS where HTTP/2 is used - it may be relevant, but since there's no error message, it's hard to tell. Any idea why PATCH endpoint causes such issues? My next step would be to try configure HTTP/2 as https://ktor.io/docs/advanced-http2.html, but since it works with the rest of requests, I'm not sure if I need it 🤷
    ✅ 1
    g
    a
    • 3
    • 13
  • a

    Aleksandr Ivanov

    08/09/2021, 2:07 PM
    I have a problem in my multiplatform project on iOS with InvalidMutabilityException while uploading a file via KTOR. I found an issue which is marked as fixed in 1.6.2, but in my case it doesn’t help. I tried to reproduce my problem based on
    client_mpp
    example and found that for ByteArray with size 100 problem is not happened, but for size 200 I got an exception. here is the code of modified
    ApplicationApi
    @SharedImmutable
    internal expect val ApplicationDispatcher: CoroutineDispatcher
    
    class ApplicationApi {
    
        // 100 - ok, 200 - kotlin.native.concurrent.InvalidMutabilityException: mutation attempt of frozen <object>
        private val SIZE = 200;
    
        private val client = HttpClient()
    
        private val address = Url("<https://cors-test.appspot.com/test>")
    
        fun about(callback: (String) -> Unit) {
            GlobalScope.launch(ApplicationDispatcher) {
                val result: String = <http://client.post|client.post> {
                    url(address.toString())
                    val filename = "test"
                    val mimeType = "image/png"
                    val filePart = formData {
                        val key = "photo"
                        val headers = Headers.build {
                            append(HttpHeaders.ContentDisposition, "filename=$filename;type=$mimeType")
                        }
                        append(key, ByteArray(SIZE), headers)
                    }
                    body = MultiPartFormDataContent(filePart)
                }
    
                callback(result)
            }
        }
    }
    a
    • 2
    • 6
  • c

    csieflyman

    08/10/2021, 4:11 AM
    Hi I set ktor.deployment.watch in my project with gradle multi-projects build on windows, but I got an error. I use ktor 1.6.2
    a
    • 2
    • 4
  • m

    Matias Reparaz

    08/11/2021, 2:06 PM
    Hi, I had the next scenario, some client calls a service A with header H, service A needs to call service B propagating the same header H. Is there any feature, or plug-in, or something to do this without moving around this information all over the A service? I’m using ktor client and server in each service
    a
    m
    • 3
    • 4
  • c

    colintheshots

    08/11/2021, 2:40 PM
    With the new bearer token client auth feature, our app has two kinds of oauth tokens: authenticated and unauthenticated. Each has a separate token and refresh token. The unauthenticated tokens are used for guest users. I'd like to figure out a way to replace the guest tokens after the user has authenticated with either user/pw or social token, but the current feature seems pretty limited. Does anyone know how I might accomplish this? Should I create a new client?
    a
    • 2
    • 9
  • l

    Luca Gentile

    08/11/2021, 3:43 PM
    Hello, I would like that when parsing a body request in
    call.receive<FooRequest>()
    to sanitize all fields declared as String in
    FooRequest
    What would you suggest?
    a
    e
    • 3
    • 14
  • n

    Nikola Milovic

    08/12/2021, 11:40 AM
    Using Ktor http client to make a request to my Nodejs backend. Tried sending a request manually and it is working, tried with my app, the body is missing. So it has to be something with my setup
    val data = JSONObject()
            data.put("email", "email")
            data.put("name", "testname")
            data.put("companyName", "testcompname")
    
            return singleFromCoroutine {
                try {
                    val response: HttpResponse =
                        <http://client.post|client.post>("${serverUrl}${apiEndpoint}/account") {
                            body = data.toString()
                            contentType(ContentType.Application.Json)
                        }
    Not sure what is happening, I'll post the entire request that gets received by the server
    a
    • 2
    • 5
  • d

    DMITRY.

    08/12/2021, 7:32 PM
    What's _application path_? https://ktor.io/docs/serving-static-content.html#folders Root directory of my project?
    o
    m
    • 3
    • 2
  • h

    Henry

    08/12/2021, 9:12 PM
    any chance of some feedback on my PR for https://youtrack.jetbrains.com/issue/KTOR-3027?
    a
    • 2
    • 1
Powered by Linen
Title
h

Henry

08/12/2021, 9:12 PM
any chance of some feedback on my PR for https://youtrack.jetbrains.com/issue/KTOR-3027?
a

Aleksei Tirman [JB]

08/13/2021, 8:42 AM
Please write a test for your change
View count: 4