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

    bitkid

    07/31/2020, 6:36 AM
    is it possible to access a file which is part of a multipart request in a streaming way? (without being written to disk/memory) It seems when i do call.receiveMultipart() and then loop over the parts, it returns the part only when it has been completely written. Any way to avoid that?
    • 1
    • 1
  • h

    hhariri

    07/31/2020, 11:47 AM
    Here’s a teaser of what’s going on
    😍 2
    :kotlin-flag: 3
    ❤️ 35
    👍 17
    n
    • 2
    • 4
  • j

    Jorge R

    08/01/2020, 2:52 PM
    Hi all I've shared a small demonstration project in Github about a basic Ktor API server with a clean architecture. I would really appreciate some feedback about it. It is handling multiple environment configurations, content negotiation, jwt authentication and database connection. It is also including docker compose deployment file to be plug and play. Right now I'm working in creating test examples for each layer. I hope you like it and it can be helpful for those starting with this amazing tool. I'm open so solve doubts and help if you start your project following this architecture. Thank you! https://github.com/mathias21/KtorEasy
    🎉 1
    s
    j
    j
    • 4
    • 10
  • d

    Dominik wuttke

    08/01/2020, 6:31 PM
    Is it possible to have modules in a different sourcefolder than the starting engine? When i set a 2nd sourcefolder in the projectsettings and add a module there I can't add this module to the config. It can't find the fully qualified name, but when I place the same module in the same sourcefolder as the engine starting module it works without a problem. Is there a way to add module from different sourcefolders? The idea behind this is to create small modules which can be switched in and out of a greater environment and having one mainmodule which installs the necessary features.
    j
    • 2
    • 3
  • m

    Matthieu Stombellini

    08/03/2020, 7:37 PM
    Hello, how can I retrieve a session arbitrarily? That is, I have sessions using a header, everything being stored on the server, the client only transmits a session ID in the header. I need to be able to retrieve the session with its ID without the header being in the call. How can I do that? In other words, how can I retrieve any session given only the session's ID?
    c
    a
    • 3
    • 7
  • s

    savrov

    08/03/2020, 9:58 PM
    @Serializable
    class SomeRequestBody(
        @SerialName("name_field")
        val name: String?
    )
    In KTOR Server, I have defined EP with such a request body. The problem is, that it works, if json looks like:
    {
      "name": "some-name-string"
    }
    but does not work if im trying to do the same with
    {
      "name_field": "some-name-string"
    }
    Do you know how to fix it? P.S. Content negotiation is enabled in application module like
    install(ContentNegotiation) {
       gson {
          setPrettyPrinting()
       }
    }
    Thank you in advance
    j
    • 2
    • 12
  • n

    Nikky

    08/04/2020, 2:43 PM
    i am using ktor-client-websockets and i cannot get the websocket to close cleanly, not sure if it is my fault or the server not responding to close frames..
    client.websocket(host, port, path) {
        for(frame in incoming) {
            // a `break` somewhere in here
        }
     
        close(CloseReason(CloseReason.Codes.GOING_AWAY, "OK"))
        <http://logger.info|logger.info> { "sent close" }
    }
    <http://logger.info|logger.info> { "websocket closed" }
    i see the
    sent closed
    log message but after that it hangs is there any other way to close the websocket ? PS: seems like it works better when not using CIO engine maybe such incompabilities should be put in the docs ?
    a
    • 2
    • 1
  • j

    jeggy

    08/04/2020, 10:48 PM
    as a ktor feature, what would be the correct way to add my own custom StatusPages for my specific exceptions? I have a feature that attaches it self to the routing feature, but I don't know how to attach to the StatusPages feature also without interfering with anything else that the user has set up for their own other stuff.
    j
    • 2
    • 2
  • c

    codec

    08/06/2020, 3:08 AM
    If a user logs out of your ktor app, how do you prevent the browser’s “back button” from letting them back in?
    a
    m
    • 3
    • 5
  • j

    ja.son

    08/06/2020, 6:38 AM
    I want to deploy the ktor server in places like aws or Azure, is there a related example?
    t
    • 2
    • 1
  • h

    Hank

    08/06/2020, 7:17 AM
    Hello everyone, I got problems with deploy my Ktor application to Google App Engine. I followed this tutorial, which is from Google Cloud Community, I stuck with gradle setting. It showed “Could not get unknown property ‘appengineRun’ for root project” at last line of the gradle. Here is my gradle
    buildscript {
        repositories {
            jcenter()
        }
    
        dependencies {
            classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
            classpath "com.google.cloud.tools:appengine-gradle-plugin:$appengine_plugin_version"
        }
    }
    
    apply plugin: 'kotlin'
    apply plugin: 'war'
    apply plugin: 'application'
    apply plugin: 'com.google.cloud.tools.appengine'
    
    appengine.deploy.projectId = 'GCLOUD_CONFIG'
    appengine.deploy.version = 'GCLOUD_CONFIG'
    
    group 'dev.hankli'
    version '1.0.0'
    mainClassName = "io.ktor.server.netty.EngineMain"
    
    sourceSets {
        main.kotlin.srcDirs = main.java.srcDirs = ['src']
        test.kotlin.srcDirs = test.java.srcDirs = ['test']
        main.resources.srcDirs = ['resources']
        test.resources.srcDirs = ['testresources']
    }
    
    webAppDirName = 'webapp'
    
    repositories {
        mavenLocal()
        jcenter()
    }
    
    dependencies {
        implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
        implementation "io.ktor:ktor-server-netty:$ktor_version"
        implementation "ch.qos.logback:logback-classic:$logback_version"
        implementation "io.ktor:ktor-server-core:$ktor_version"
        implementation "io.ktor:ktor-locations:$ktor_version"
        implementation "io.ktor:ktor-server-sessions:$ktor_version"
        implementation "io.ktor:ktor-auth:$ktor_version"
        implementation "io.ktor:ktor-auth-jwt:$ktor_version"
        implementation "io.ktor:ktor-gson:$ktor_version"
        implementation 'com.google.firebase:firebase-admin:6.14.0'
        implementation "com.desmondtzq.ktor:ktor-auth-firebase:1.0.1"
        testImplementation "io.ktor:ktor-server-tests:$ktor_version"
    
        implementation "org.jetbrains.exposed:exposed-core:$exposed_version"
        implementation "org.jetbrains.exposed:exposed-dao:$exposed_version"
        implementation "org.jetbrains.exposed:exposed-jdbc:$exposed_version"
        implementation "org.jetbrains.exposed:exposed-jodatime:$exposed_version"
        implementation "org.postgresql:postgresql:$postgres_version"
        implementation "com.zaxxer:HikariCP:$hikaricp_version"
    
        providedCompile "com.google.appengine:appengine:$appengine_version"
    }
    
    task run(dependsOn: appengineRun) // Could not get unknown property 'appengineRun' for root project
    And I’ve tried to use the Cloud Code plugin in IntelliJ IDE to run my code and there was an error that showed “Please first confirm that there is a properly placed appengine-web.xml file”, even though I’ve set the directions. Is anyone can help me out or give me some suggestions, really appreciate.🙏
    j
    m
    • 3
    • 3
  • j

    Jan Stoltman

    08/06/2020, 7:19 AM
    Hey guys, I have a quick question. What library do you use for autogeneration of api documentation? I would like to get a list of endpoint + models or something in this direction. I tried using Ktor-OpenAPI-Generator but it doesn't seem to be working that well with Ktor Locations. Any alternatives?
    h
    a
    • 3
    • 3
  • l

    ley

    08/06/2020, 9:40 AM
    When is the next release?
    n
    • 2
    • 1
  • d

    Dominik wuttke

    08/06/2020, 8:54 PM
    Is it possible to do server-side rendering of an angular app in ktor? If yes, is there a guide on how to do it?
    n
    • 2
    • 3
  • k

    Krystian Rybarczyk

    08/07/2020, 8:58 AM
    hey guys, has anyone tried using ktor
    1.3.2-1.4.0-rc
    ? I’ve updated my kotlin version and ktor version in gradle, but gradle fails to build with the below. This is strange, because I can see these in maven central (which I have declared to use in my build config):
    repositories {
        mavenLocal()
        jcenter()
    }
    Could anyone give me a hand here?
    j
    • 2
    • 2
  • e

    Eric Ampire [MOD]

    08/08/2020, 1:25 PM
    Which converter should I use to receive data from a form as an object, I use thymeleaf as a template engine, After using the
    GsonConvert
    install(ContentNegotiation) {
        register(ContentType.Any, GsonConverter())
    }
    The statement generate an exception.
    post("save") {
        val data = call.receive<MyClass>()
    }
    👀 1
    w
    n
    • 3
    • 3
  • g

    Gunslingor

    08/09/2020, 5:35 PM
    BIG Question: What do yall do for front end frameworks with Ktor? I heard KotlinJS isn't really being developed or might be retired, I never really got it working with ktor. I don't get why ktor has CSS and HTML DSL inherent but not js. So what do people do for front end, just create JS files in the resources folder? For libraries that makes sense I guess but not custom frontend code, and I wouldn't mind moving away from JS. I mean if I write in JS why would someone write in kotlin HTML/CSS, module parts would end up isolated most likely. Trying to understand real world practical solutions, modern too... options. Assume I'm making a site like Wix, so I might use stuff like grapeJS and 3D junk.
    r
    s
    d
    • 4
    • 39
  • h

    hhariri

    08/10/2020, 7:25 AM
    <!here> One of the things folks have asked us for is more insight into what we’re planning for Ktor. Here’s a roadmap for 2020-2021 https://blog.jetbrains.com/ktor/2020/08/10/ktor-roadmap-for-2020-2021/
    :kotlin-flag: 7
    👍 29
    a
    • 2
    • 4
  • j

    John O'Reilly

    08/10/2020, 8:28 AM
    "Our next release, which is 1.4.0, is targeted for the week of August 17th. This release will be compatible with the upcoming Kotlin 1.4 release" Will this have support for
    native-mt
    version of kotlinx coroutines (assuming that's still branch in 1.4....though I guess (hope) it might be in "official" version by then?)
    🎉 7
    ➕ 6
    h
    • 2
    • 2
  • g

    gps

    08/10/2020, 9:26 AM
    Hey everyone, not sure if this is the right place to ask (my apologies if this is not the right place) - has anyone tried using Koin with Ktor, and creating a scope that lasts for the duration of a request? For example, if I wanted to be able to inject something like a trace id, how would I go about doing that? Thanks!
    e
    j
    • 3
    • 6
  • g

    Gunslingor

    08/10/2020, 1:15 PM
    How does implement(npm("[three.js route]")) work? I mean, can you then import this into the KotlinJS and use it somehow, how do I develop static routes for this in ktor? I have my JS packages working in KotlinJS by putting them in resources before creating the fat jar.
    • 1
    • 1
  • g

    Gunslingor

    08/10/2020, 2:00 PM
    browserdevelopmentrun is a task that I think comes from KotlinJS plugin. I think it runs the front end only, but then how does this really provide any usefulness when routing is in the backend Ktor? ie. I have the task config, what url do I go to to see the page?
    target {
        browser {
            webpackTask {
                outputFileName = "MyProjectName.js"
            }
            runTask {
                dependsOn("build")
                devServer = devServer?.copy(
                    port = 8088,
                    proxy = mapOf("/api" to "<http://localhost:8080>")
                )
            }
        }
    }
    c
    r
    • 3
    • 91
  • g

    Gunslingor

    08/11/2020, 2:15 AM
    What do yall use for user managment? Wondering if I need to program basic user management again for the billionth time... in the millionth language, lol... or if a package exists.
    ➕ 2
    j
    • 2
    • 3
  • h

    Hank

    08/11/2020, 9:37 AM
    Hi guys, how can I switch my different configurations when running a Ktor application? I want to know both of in IntelliJ and command line.
    g
    j
    • 3
    • 10
  • g

    Gunslingor

    08/11/2020, 1:17 PM
    Is there a better way to make the front end kotlinJS talk to the backend Ktor than this:
    a
    s
    • 3
    • 7
  • l

    Laurence

    08/11/2020, 8:23 PM
    Hi Everyone 🙂 This is my first post here! I have been trying to figure out how to upload a file to S3 using bits and pieces that I found online, but just can't get it to work. I want to use
    call.receiveMultipart()
    and then use the input stream, but when I test using postman it just hangs and doesn't fail with an error. In Gradle I have:
    // AWS S3
      implementation platform('com.amazonaws:aws-java-sdk-bom:1.11.7')
      implementation 'com.amazonaws:aws-java-sdk-s3'
    For the S3 client and upload function I am using:
    private val s3Client = AmazonS3Client(
        BasicAWSCredentials(S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY)
      ).apply {
        withRegion<AmazonWebServiceClient>(Regions.US_EAST_1)
        setS3ClientOptions(
          S3ClientOptions.builder()
            .setPathStyleAccess(true).build()
        )
      }
    
    
    fun uploadFileToS3(key: String, inputStream: InputStream, metadata: ObjectMetadata): PutObjectResult =
       s3Client.putObject(BUCKET_NAME, key, inputStream, metadata)
    Then the route is calling:
    val multiPartData = call.receiveMultipart()
    
            multiPartData.forEachPart { part ->
              when (part) {
                is PartData.FileItem -> {
    
                  val key = "profile-image/${part.originalFileName ?: "unknown-file"}"
    
                  part.streamProvider()
                    .use { inputStream ->
    
                      val bytes: ByteArray = IOUtils.toByteArray(inputStream)
                      val metadata = ObjectMetadata()
                      metadata.contentLength = bytes.size.toLong()
                      val byteArrayInputStream = ByteArrayInputStream(bytes)
    
                      AwsS3.uploadFileToS3(
                        key,
                        byteArrayInputStream,
                        metadata
                      )
                    }
                }
                else -> call.respond(HttpStatusCode.InternalServerError, JSONObject(mapOf("err" to "Error uploading file")))
              }
            }
    
            call.respond(
              HttpStatusCode.OK,
              JSONObject(mapOf("msg" to "Image uploaded successfully"))
            )
    Hoping someone can spot where I'm going wrong 🙂 Thanks!
    e
    • 2
    • 3
  • r

    rudolf.hladik

    08/12/2020, 11:15 AM
    Hi, what dependency should I specify to be able to use Ktor client on ios in common module with kotlin 1.4-rc? i’ve tried
    implementation("io.ktor:ktor-client-core:1.3.2-1.4.0-rc")
    but it was not enough, it wants engine so i’ve tried
    implementation("io.ktor:ktor-client-cio:1.3.2-1.4.0-rc")
    but it doesn’t work 😞
    👀 2
    j
    • 2
    • 3
  • m

    manlan

    08/12/2020, 6:13 PM
    @Serializable
    data class Reader(
            var name : String = "",
            var photoUrl : String = "",
            var address : Address = Address())
    Kotlinx Serialization setup
    r
    j
    • 3
    • 12
  • j

    John O'Reilly

    08/13/2020, 10:35 AM
    What's current recommended approach for using Swagger and Ktor? I see there's a few plugins but some don't seem to be being maintained. Also, seems to be a few approaches e.g. auto generate swagger json from routes, or for example visa versa.
    h
    h
    • 3
    • 4
  • m

    Mgj

    08/13/2020, 12:13 PM
    On a client i would like to use JWT auth. These JWT expires sometimes, so i would like to intercept every request and look for a 401 or 403 response, refresh my token and retry the request. How do i do this? I found
    HttpResponseValidator
    which seems useful, but how do i: 1. Perform a refresh request 2. Retry the failed request Perhaps im better off wrapping my ktor calls in a helper, and handle it there instead of trying to use 
    HttpResponseValidator
    ?
    j
    e
    • 3
    • 7
Powered by Linen
Title
m

Mgj

08/13/2020, 12:13 PM
On a client i would like to use JWT auth. These JWT expires sometimes, so i would like to intercept every request and look for a 401 or 403 response, refresh my token and retry the request. How do i do this? I found
HttpResponseValidator
which seems useful, but how do i: 1. Perform a refresh request 2. Retry the failed request Perhaps im better off wrapping my ktor calls in a helper, and handle it there instead of trying to use 
HttpResponseValidator
?
j

jorge.rego

08/13/2020, 12:39 PM
How do you do that in your server or in your client?
In server side you can install JWT Authentication feature and validate tokens by JWT validator. All routes inside authentication will require to pass the JWT validator. Here you can find an example: https://github.com/mathias21/KtorEasy
m

Mgj

08/13/2020, 12:41 PM
In my client
j

jorge.rego

08/13/2020, 1:31 PM
Ktor doc is not saying anything about how to deal with token refresh, but in OkHttp3 Android you would implement a token Authenticator that will process token refresh when 401 is returned.
m

Mgj

08/13/2020, 1:38 PM
Yeah something like that would be great. Im unsure if its part of retrofit or okhttp but the `authenticator`class is very very useful for this purpose, or the more generalized interceptors. But i want to use something shared across the different platforms in my KMP project
j

jorge.rego

08/13/2020, 3:27 PM
This is what I was talking about, for sure part of the OkHttp3 lib. https://square.github.io/okhttp/4.x/okhttp/okhttp3/-authenticator/ In any case, you need to intercept http responses to automate this process, so the library you use should allow that.
e

edenman

08/13/2020, 8:12 PM
i just have a helper
suspend fun doRequest
that i run all my requests through and then recursively call it based on response codes and auth token stuff
👍 1
View count: 1