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

    otakusenpai

    03/11/2019, 6:29 PM
    Hello. I'm trying to make a test Ktor server using raw sockets. But IDK where ton start. The examples in ktor.io are for http servers. Can anyone guide me in this matter?
    • 1
    • 2
  • r

    ribesg

    03/12/2019, 1:26 PM
    Caused by: kotlin.NotImplementedError: An operation is not implemented: Obtaining serializer from KClass is not available on native due to the lack of reflection. Use .serializer() directly on serializable class.
    Ok, but how are you supposed to do that? Is it a bug in ktor?
    e
    • 2
    • 4
  • r

    ribesg

    03/12/2019, 3:02 PM
    It prints
    kotlin.TypeCastException
    when I create an
    HttpClient
    using this on iOS
    object HttpCliiFactory {
    
        fun create(
            config: HttpClientConfig<*>.() -> Unit = {},
            serializer: KotlinxSerializer.() -> Unit = {}
        ) =
            HttpClient {
                expectSuccess = false
                install(MyLoggingFeature)
                install(ExpectSuccess)
                install(JsonFeature) {
                    this.serializer = KotlinxSerializer(Json.nonstrict).apply(serializer)
                }
                config()
            }
    
    }
    👀 1
    • 1
    • 2
  • s

    ShreemanArjun

    03/13/2019, 2:35 AM
    How i serve static files of a folder to my ktor html dsl files.. help me
    b
    • 2
    • 4
  • n

    Nikolai

    03/13/2019, 7:21 AM
    Hi, everyone I am sorry for asking again, but I need to know answer if it’s possible. Here is my original post (https://kotlinlang.slack.com/archives/C0A974TJ9/p1549615027584900) it’s about using ktor on Android 4.4.2 - 5.0.1. I am sending POST request with body-type json. But in the output in proxy logger content-type of the request is changed to “text/html; charset=iso-8859-1”. Is it bug or expected behaviour? I need to change something? Maybe I need to write my own client? Thanks.
    e
    • 2
    • 4
  • v

    Vladimir Petrakovich

    03/13/2019, 1:05 PM
    Hi! I'm wondering why query parameters can override path parameters with the same name. For example I have such a route in the application:
    route("/{id}") {
        get { println(call.parameters["id"]) }
    }
    Given a request
    GET /foo?id=bar
    the printed value will be "bar", not "foo". It looks like this is intended behavior (see https://github.com/ktorio/ktor/blob/d4e1a7caaa031fb466beb1cc102192cc88623bfe/ktor-server/ktor-server-core/jvm/src/io/ktor/routing/RoutingApplicationCall.kt#L25), but why?
    r
    • 2
    • 1
  • v

    Vinicius Carvalho

    03/13/2019, 2:50 PM
    when user Ctrl+C app, that lambda never gets called
    r
    • 2
    • 12
  • a

    avolkmann

    03/13/2019, 3:17 PM
    Is it intended that the client can't resolve urls without a protocol?
    127.0.0.1:3500
    works find with curl, but not from ktor
    e
    e
    • 3
    • 8
  • c

    cy

    03/13/2019, 3:57 PM
    @serebit @mp see the changelog: https://github.com/ktorio/ktor/blob/master/CHANGELOG.md
    👍🏿 1
    s
    • 2
    • 1
  • s

    stanislav

    03/13/2019, 5:19 PM
    Introduced multiplatform websockets: jvm, js.
    Not yet available for iOS?
    e
    • 2
    • 5
  • v

    Vinicius Carvalho

    03/13/2019, 8:07 PM
    for(i in 0..invocations){
                launch {
                    val response = client.call(host).response
                    val result = mapper.readValue<FunctionResponse>(response.readBytes())
                    val requestTime = response.responseTime.timestamp - response.requestTime.timestamp
                    channel.send(ExecutionEvent(requestTime = requestTime, pause = result.pause))
                }
            }
    e
    • 2
    • 9
  • w

    walla

    03/14/2019, 7:15 AM
    Hi! How much does it make sense to do all the work with databases inside withContext(Dispatchers.IO) block? I mean backend application.
    g
    j
    • 3
    • 15
  • d

    davidasync

    03/14/2019, 9:19 AM
    Hello after migrating my http client from jetty to ktor, my service experience high cpu and high open file, any idea why this happened ? And here my code snippet, at function send async
    -.kt
    👀 1
    e
    g
    • 3
    • 18
  • j

    Jonas Bark

    03/14/2019, 12:27 PM
    1_2_0-alpha-1.txt
    e
    • 2
    • 2
  • o

    obobo

    03/14/2019, 2:25 PM
    If I use
    JsonFeature
    and make calls like
    httpClient.get<DataClass>("url")
    is the underlying httpResponse automatically closed, or does it expect me to close httpClient after each call? I haven't been able to find where the response is closed.
    r
    e
    r
    • 4
    • 8
  • n

    Nikolai

    03/14/2019, 3:35 PM
    Hi, everyone Is there any way to quickly ping any address to check if internet connection available (I mean to check if internet available in general, not to current address)? P.S. Developing multiplatform project and this function will be in common module.
    r
    • 2
    • 2
  • f

    fcosta

    03/14/2019, 4:46 PM
    Hi! Is there any CLI tool to generate a project with ktor?
    e
    c
    • 3
    • 4
  • g

    galex

    03/15/2019, 7:02 AM
    Hello, what is the best way to deal with this error in Kotlin/Native:
    kotlin.NotImplementedError: An operation is not implemented: Obtaining serializer from KClass is not available on native due to the lack of reflection. Use .serializer() directly on serializable class.
    After adding the
    .serializer()
    to
    Json.stringify
    I get the following error and I am not sure how to specify the serializer() for the receiving/parsing part:
    io.ktor.client.call.ReceivePipelineException: Fail to run receive pipeline
    Here’s my request:
    val result: ActionResponse = <http://networkHttpClient.post|networkHttpClient.post> {
        url(address)
        body = TextContent(Json.stringify(Event.serializer(), event), contentType = ContentType.Application.Json)
    }
    e
    • 2
    • 14
  • r

    Riccardo Montagnin

    03/18/2019, 6:40 AM
    Hello everyone. What does the Ktor team use in order to publish the Dokka generated MD file to their documentation website?
    e
    • 2
    • 3
  • a

    avolkmann

    03/18/2019, 9:26 AM
    Has anyone experienced this:
    2019-03-18 10:25:09,867 [nettyCallPool-4-3] INFO  ktor.application - 401 Unauthorized: POST - /match
    2019-03-18 10:25:10,128 [nettyCallPool-4-4] INFO  ktor.application - 200 OK: POST - /match
    On call, the server first logs 401, then 200
    r
    • 2
    • 7
  • n

    Nikolai

    03/18/2019, 12:50 PM
    Hi, everyone I am using OkHttp Engine for HttpClient. And for POST request I am using EmptyContent body-type But OkHttp still complaining : POST requests must have Body. Setting EmptyContent is not enough? How can I set dummy empty bode?
    e
    r
    • 3
    • 3
  • r

    Riccardo Montagnin

    03/19/2019, 9:32 AM
    Hello everyone, I'm trying to publish a multiplatform project to Maven. I've copied Ktor .gradle files, but when I try to run the
    publishToMavenLocal
    task I get the following error:
    * Where:
    Script 'D:\Coding\Borsellino\gradle\publish.gradle' line: 45
    
    * What went wrong:
    Could not evaluate onlyIf predicate for task ':borsellino-eth:publishKotlinMultiplatformPublicationToMavenLocal'.
    > Cannot get property 'isLinuxHost' on extra properties extension as it does not exist
    I've made sure that I applied the
    publish.gradle
    file properly inside my project
    build.gradle
    file as follows:
    if (!rootProject.ext.skipPublish.contains(project.name)) {
        apply from: rootProject.file('gradle/publish.gradle')
    }
    Where should I look to check I got everything properly set up?
    e
    • 2
    • 4
  • o

    obobo

    03/19/2019, 2:19 PM
    Is there some way to install a Feature on a per-route basis?
    c
    • 2
    • 1
  • s

    stanislav

    03/19/2019, 2:46 PM
    Hi, I'm experiencing crash @ iOS. Stack & Crash log in thread
    e
    • 2
    • 10
  • o

    obobo

    03/19/2019, 4:43 PM
    Also, I'm using
    ContentNegotiation
    , and trying to use
    receiveOrNull
    to 'safely' get a POST body, and it feels much less useful/safe than I'd expect it to be. If I send an empty body or try to instance a data object with non-nullable fields
    receiveOrNull
    will throw an exception. Is this by design?
    b
    • 2
    • 2
  • t

    tjb

    03/20/2019, 12:08 AM
    dumb question maybe...i want to help contribute but is there a guideline on "how to get started" or something similar? i want to tackle an issue in
    kt-server-core
    but am not 100% sure how to test my changes...is there a way to bundle this so i can test?
    a
    • 2
    • 2
  • e

    einar

    03/20/2019, 8:42 PM
    Is there a way to, using the ktor client, handle a response that can be of different type when performing a POST request? I was thinking of using
    sealed class
    for this but I’m falling short when it comes to supporting the de-serialization of the response. So something like
    sealed class ApiResponse
    <http://client.post|client.post><ApiResponse> {  }
    @Serializable data class ErrorResponse(...) : ApiResponse()
    @Serializable data class SuccessResponse(..) : ApiResponse()
    r
    • 2
    • 6
  • n

    napperley

    03/21/2019, 4:23 AM
    Trying to test the server (runs on a different host and port) via the Kotlin Test library, and have encountered a situation where when running a test it runs indefinitely. Below is the test logic:
    import io.kotlintest.specs.FunSpec
    import io.ktor.application.Application
    import io.ktor.http.HttpMethod
    import io.ktor.http.HttpStatusCode
    import io.ktor.server.testing.handleRequest
    import io.ktor.server.testing.withTestApplication
    import kotlin.test.assertEquals
    
    class RouteTest : FunSpec() {
        init {
            testHomeRouteExists()
        }
    
        private fun testHomeRouteExists() = test("homeRouteExists") {
            withTestApplication(Application::main) {
                with(handleRequest(HttpMethod.Get, "/")) {
                    assertEquals(expected = HttpStatusCode.OK, actual = response.status())
                    assertEquals(expected = "Battery Info Server\n", actual = response.content)
                }
            }
        }
    }
    d
    • 2
    • 6
  • j

    JoakimForslund

    03/21/2019, 8:26 AM
    Am I understanding this correctly, ktor raw sockets is not supported on iOS right now?
    c
    • 2
    • 2
  • g

    Gary

    03/22/2019, 2:51 AM
    Hi there, sorry new to ktor - wondering if someone could point me in the direction of what is the best practice to validating that a header is present in a request. E.g. something equivalent to Spring
    @RequestHeader(value = "X-API-Key", required = true)
    👆 1
    s
    d
    • 3
    • 4
Powered by Linen
Title
g

Gary

03/22/2019, 2:51 AM
Hi there, sorry new to ktor - wondering if someone could point me in the direction of what is the best practice to validating that a header is present in a request. E.g. something equivalent to Spring
@RequestHeader(value = "X-API-Key", required = true)
👆 1
s

spand

03/22/2019, 7:22 AM
Pretty sure there is a
header
function in the routing setup
d

dave08

03/24/2019, 5:27 AM
Maybe a little custom Feature that hooks the requests and returns whatever if the header's not there...
g

Gary

03/25/2019, 12:08 AM
We ended up writing something like this. Feels a bit hacky though 😕
fun Route.requireHeaders(vararg headerNames: String, build: Route.() -> Unit): Route {
    val selector = HttpHeaderExistRouteSelector(headerNames)
    return createChild(selector).apply(build)
}
And then using it in the routes
route("endpoint") {
            requireHeaders("REQUIRED_HEADER", "REQUIRED_HEADER_2") {
                get("available") {
...                    
                }
            }
        }
d

dave08

03/25/2019, 11:10 AM
Not a bad solution 😉. How would you have preferred it to look?
View count: 2