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

    danielspeixoto

    12/09/2017, 12:15 AM
    Is there a way to embed servlets in ktor?
    o
    • 2
    • 2
  • l

    lbaresse

    12/12/2017, 7:26 PM
    @rocketraman actually it's not really a dependency. I guess you're talking about KoinComponent interface ? It's just a maker interface on which we are providing functions extensions. We could have done theses extensions on the
    Any
    kotlin's type but It seems to us it was not so clean to extend it.
    r
    d
    • 3
    • 6
  • o

    orangy

    12/12/2017, 7:52 PM
    DI discussion is clearly offtopic, but I agree that dependency of user code on DI is not a “pure concept”, however if you want auto-discovery (which is VERY convenient during development/prototyping) via JAR scanning & reflection, you need to mark components somehow. Best of what I could ever imagine for this use case is meta-annotation. So you define your own annotation which is either annotated with DI’s annotation, or explicitly given as input to DI auto-discovery function, and then you mark your components with that annotation.
    d
    • 2
    • 1
  • s

    snrostov

    12/12/2017, 8:34 PM
    More offtopic question: what the meaning of name “ktor”?
    o
    l
    s
    • 4
    • 6
  • a

    arnaud.giuliani

    12/13/2017, 10:56 AM
    Hope it will give a better idea 🙂
    r
    • 2
    • 1
  • o

    orangy

    12/14/2017, 5:17 PM
    No, everything is fine here is freemarker: https://bintray.com/kotlin/ktor/ktor/0.9.1-alpha-8#files/io%2Fktor%2Fktor-freemarker%2F0.9.1-alpha-8
    n
    • 2
    • 13
  • g

    gotwalt

    12/14/2017, 6:08 PM
    I've got a web service going up behind a load balancer that handles SSL for me, and struggling to get CORS to work correctly. All requests are authenticated using an oauth2 Authorization header. I'm configured as below, but not receiving an Access-Control-Allow-Origin in the OPTIONS response. Any ideas?
    install(CORS) {
            method(HttpMethod.Options)
            method(HttpMethod.Put)
            method(HttpMethod.Delete)
            header(HttpHeaders.Authorization)
            allowCredentials = true
            host("*", schemes = listOf("http", "https"))
          }
    o
    • 2
    • 9
  • a

    avolkmann

    12/19/2017, 7:00 AM
    @tjb If you want an example, here is a recent one I wrote: https://github.com/goreRatzete/kobalt-test . Basically everything ktor related is in the server package.
    t
    • 2
    • 1
  • t

    Tristan Caron

    12/21/2017, 1:20 PM
    Hello, Someone is using
    ktor-auth-jwt
    ? I cannot use it. Gradle is throwing me an error
    cannot resolve
    . But others packages are okay (
    ktor-auth
    works for instance).
    o
    • 2
    • 2
  • s

    spand

    12/21/2017, 1:36 PM
    Is ktor known to work with the commandline shortener in idea?
    o
    • 2
    • 6
  • o

    orangy

    12/21/2017, 6:30 PM
    We don’t (yet) have Redis integration, but basically you need to implement
    SessionStorage
    k
    • 2
    • 1
  • t

    tjb

    12/27/2017, 9:18 PM
    question: is there something similar to
    @Value
    from Spring in Ktor?
    b
    k
    • 3
    • 7
  • w

    wineluis

    01/01/2018, 2:53 PM
    when I do this it seems to work
    call.respondText(json.toJsonString(), ContentType.Application.Json, HttpStatusCode.OK)
    n
    • 2
    • 3
  • i

    Ian

    01/01/2018, 11:33 PM
    Having a bit of a WebSocket headache, I’ve followed the ChatApplication example[1] fairly closely, but when my browser attempts to send a message it gives me a
    (index):77 WebSocket is already in CLOSING or CLOSED state
    error. There is no indication that the
    webSocket { … }
    handler is called at all. Does anyone have any suggestions about how I can figure out why the server is closing the webSocket connection or failing to open it in the first place? [1] https://github.com/ktorio/ktor/blob/master/ktor-samples/ktor-samples-websocket/src/io/ktor/samples/chat/ChatApplication.kt
    g
    • 2
    • 4
  • l

    louiscad

    01/02/2018, 2:14 PM
    Hi, how can I set up a Kotlin microservice using ktor on a public cloud such as Google Cloud? I'm particularly interested in Google Cloud supported because they are carbon neutral, and provide DDoS protections along with a competitive price and more, and I want to try cutting edge Kotlin stuff, hence why ktor. Also I wonder if JetBrains is not already in talks with Google about that since they already have some partnership for Android + Kotlin and also Android Studio
    d
    k
    • 3
    • 8
  • o

    orangy

    01/05/2018, 5:33 PM
    Anyone still uses it? Why?
    t
    l
    • 3
    • 8
  • l

    Lucas

    01/12/2018, 9:41 AM
    Can anyone explain why the test below throws an exception? The code works when consuming the endpoint using the browser.
    Exception in thread "ForkJoinPool.commonPool-worker-2 @coroutine#4" java.lang.IllegalStateException: Unsupported opcode b
    	at io.ktor.websocket.FrameParser.getFrameType(FrameParser.kt:26)
    	at io.ktor.websocket.FrameParser.parseHeader1(FrameParser.kt:69)
    	at io.ktor.websocket.FrameParser.handleStep(FrameParser.kt:56)
    	at io.ktor.websocket.FrameParser.frame(FrameParser.kt:52)
    	at io.ktor.websocket.WebSocketReader.parseLoop(WebSocketReader.kt:55)
    	at io.ktor.websocket.WebSocketReader.readLoop(WebSocketReader.kt:46)
    	at io.ktor.websocket.WebSocketReader$readerJob$1.doResume(WebSocketReader.kt:21)
    	at kotlin.coroutines.experimental.jvm.internal.CoroutineImpl.resume(CoroutineImpl.kt:54)
    	at kotlinx.coroutines.experimental.DispatchTask.run(CoroutineDispatcher.kt:123)
    	at java.util.concurrent.ForkJoinTask$RunnableExecuteAction.exec(ForkJoinTask.java:1402)
    	at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
    	at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)
    	at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
    	at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)
    @Test
    fun `It can get a car using cars ws endpoint`() = withTestApplication(Application::main) {
        val webSocketRequest = handleWebSocket("/cars", {
            body = """{"model":"Ford Mustang","releaseYear":1976}"""
        })
    
        webSocketRequest.let { call ->
            call.response.awaitWebSocket(Duration.ofSeconds(20))
    
            val (model, releaseYear) = jacksonObjectMapper().readValue<Car>(call.response.content!!)
            assertEquals(model, "Ford Mustang")
            assertEquals(releaseYear, 1789)
        }
    }
    routing {
            val messages = ConflatedBroadcastChannel<Car>()
            webSocket("/cars") {
                messages.openSubscription().use { subscription ->
                    subscription.consumeEach {
                        println("Sending $it")
                        outgoing.send(Frame.Text(jacksonObjectMapper().writeValueAsString(it)))
                    }
                }
            }
    
            launch {
                while (isActive) {
                    delay(1000L)
                    messages.offer(Car(model = "Ford Mustang", releaseYear = 1976))
                }
            }
        }
    c
    • 2
    • 3
  • f

    frellan

    01/12/2018, 12:19 PM
    Yeah Im reading up on that now, it has very extensive documentation. I guess I would need some object at least, logging works currently but I just want to output stuff myself, will try and read up more, was just thinking if there was some simple snippet available or something since just outputting stuff to the log with the correct flags must be something quite common
    o
    • 2
    • 2
  • d

    deviant

    01/12/2018, 3:57 PM
    hi! has anybody tried `ktor`+`swagger`? is it possible?
    h
    • 2
    • 1
  • f

    frellan

    01/13/2018, 9:59 AM
    It turned out that I had to enable CORS for my own port and domain, I run ktor on
    localhost:5000
    and I had to enable CORS for
    localhost:5000
    as well, which seems weird to me. I did not get the usual
    CORS not allowed header blabla
    just a
    403
    o
    • 2
    • 1
  • w

    wouterdoeland

    01/13/2018, 8:28 PM
    Is it possible to edit the ktor.io site? Then I'll add that to the docs 🙂
    t
    • 2
    • 1
  • f

    frellan

    01/14/2018, 1:44 PM
    Error: Main method not found in class ServerKt, please define the main method as:
       public static void main(String[] args)
    b
    • 2
    • 1
  • f

    frellan

    01/14/2018, 1:44 PM
    Since im not doing Java, how do one do this?
    t
    • 2
    • 4
  • o

    orangy

    01/14/2018, 5:02 PM
    @Ian it looks like you have different versions of kotlinx.coroutines coming from different dependencies, and they are at conflict
    i
    • 2
    • 16
  • d

    damian

    01/14/2018, 7:38 PM
    im kind of confused. i installed
    CORS
    (with GET, POST, OPTIONS methods,
    anyHost
    and
    exposeHeader("Access-Control-Allow-Origin")
    ) but i'm still receiving 403 for requests
    o
    • 2
    • 7
  • o

    orangy

    01/15/2018, 5:39 AM
    @noncom same issue that @Ian got above. We will try to fix it all today and release new
    alpha
    👍 5
    i
    • 2
    • 2
  • e

    elizarov

    01/16/2018, 10:02 AM
    “Extract function” (Ctrl+Alt+M) refactoring for contents of the first two, then invoke both funs in merged.
    ➕ 1
    t
    • 2
    • 1
  • a

    aeruhxi

    01/16/2018, 10:44 AM
    Hi
    install(ContentNegotiation) {
            gson {
                setDateFormat(DateFormat.LONG)
                excludeFieldsWithoutExposeAnnotation()
            }
        }
    Even with
    excludeFieldsWithoutExposeAnnotation
    , it is serializing fields without Expose. Am I missing something?
    o
    • 2
    • 2
  • s

    Sergey Chikin

    01/16/2018, 11:53 AM
    Hey guys, trying to basic async endpoint with `ktor`:
    override val route: Routing.() -> Unit
            get() = {
                get("healthz") {
                    val dbState = asyncGetDatabaseState()
    
                    var res = HealthModel(
                            status = Server.status,
                            database = dbState.await(),
                            redis = RedisHealth("null", 0)
                    )
    
                    call.respond(res)
                }
            }
    
        suspend fun getDatabaseState(): DatabaseHealth {
            delay(500) //sleep for 500ms
    
            return DatabaseHealth(
                    host = Config.config[DatabaseConfig.host],
                    database = Config.config[DatabaseConfig.database],
                    latencyMs = 500
            )
        }
    
        fun asyncGetDatabaseState() = async {
            getDatabaseState()
        }
    But I keep getting
    Caused by: io.ktor.server.engine.BaseApplicationResponse$ResponseAlreadySentException: Response has already been sent
    even though actual content is sent back to client with HTTP 200. What am I doing wrong?
    o
    n
    • 3
    • 34
  • m

    Muthu Nadar

    01/16/2018, 1:57 PM
    From where do I refer pipeline. Document seems to be incomplete http://ktor.io/advanced/pipeline.html
    o
    • 2
    • 2
Powered by Linen
Title
m

Muthu Nadar

01/16/2018, 1:57 PM
From where do I refer pipeline. Document seems to be incomplete http://ktor.io/advanced/pipeline.html
o

orangy

01/16/2018, 2:44 PM
What do you need to achieve?
m

Muthu Nadar

01/17/2018, 7:30 AM
Actually I'm new to kotlin and ktor, I was going through the document and found that it has a feature called pipeline. But when I clicked pipeline document was incomplete so I couldn't continue further.
View count: 2