https://kotlinlang.org logo
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
benchmarks
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
confetti
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
hiring-french
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
lincheck
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
Title
c

Carlos Santos

07/23/2021, 8:21 AM
Hi guys, I've been looking for this info in the internet but I couldn't find a clear answer. Let's say that I have an endpoint like: GET -> /ktor I want to create an interceptor and put it in the pipeline but only for that particular endpoint. I don't want to create an interceptor and then check the request path like in the docs. I was looking for "clean" solution like a plugin or something similar. I know that there's an interface named RootRouteSelector but I couldn't figured out how it works. Do you know if this is possible, and if so, can you point me to some docs/example. Thank you!
👍 1
a

Aleksei Tirman [JB]

07/23/2021, 8:55 AM
Could you please describe what do you want to achieve and why a route handler is insufficient?
c

Carlos Santos

07/23/2021, 9:06 AM
I want to intercept a request, get the parameters, call a second service to validate one of those parameters, save the response of the second service in cache and if everything is ok, proceed
i dont want to put this logic in the inside the route, cuz i will have multiple routes that will need this validation
j

Joost Klitsie

07/23/2021, 12:11 PM
I think you should be able to write a feature for this
that wraps around your route
a

Aleksei Tirman [JB]

07/23/2021, 12:26 PM
You can write an extension function for a
Route
and in its body, create a new route with a custom selector. In that selector, you may have a validation logic. Here is an example:
fun main() {
    embeddedServer(Netty, port = 8080) {
        routing {
            validate {
                get("/") {
                    call.respondText { "ewqe" }
                }
            }
        }
    }.start(wait = true)
}

fun Route.validate(validator: MyValidator = MyValidator(), build: Route.() -> Unit): Route {
    val newRoute = createChild(MySelector(validator))
    newRoute.build()
    return newRoute
}

class MySelector(private val validator: MyValidator): RouteSelector() {
    override fun evaluate(context: RoutingResolveContext, segmentIndex: Int): RouteSelectorEvaluation {
        if (validator.validate()) {
            return RouteSelectorEvaluation.Constant
        }

        return RouteSelectorEvaluation.Failed
    }
}

class MyValidator {
    fun validate(): Boolean {
        return true
    }
}
c

Carlos Santos

07/23/2021, 1:07 PM
Got your idea, just one more question. How can i be sure that this will always run after authenticate? Would that be like?:
...
routing {
    authenticate(...){
            validate {
                get("/") {
                    call.respondText { "ewqe" }
                }
            }
       }
}
r

Rustam Siniukov

07/23/2021, 1:47 PM
While solution from @Aleksei Tirman [JB] will work, it’s better to use interceptors instead of putting logic to
evaluate
. Something like
fun Route.validate(validator: MyValidator = MyValidator(), build: Route.() -> Unit): Route {
    val newRoute = createChild(MySelector())
    newRoute.intercept(Call) { validator() }
    return newRoute
}
c

Carlos Santos

07/23/2021, 2:24 PM
How can i make the intercept run after authenticate? I need to make it run after the authenticate and before the request being handled. That interceptor and the authenticate both run in the same fase, and i need to make it run after the call being authenticated
I could also run this while the request is being authenticated, but we have no access to the request in that context
r

Rustam Siniukov

07/23/2021, 2:34 PM
Routing keeps order of interceptors. Your interceptor should be invoked after any interceptors from parent routes, including authentication
c

Carlos Santos

07/23/2021, 2:36 PM
Thank you, i'll explore that option
...
routing {
    authenticate(...){
            validate {
                get("/") {
                    call.respondText { "ewqe" }
                }
            }
       }
}

...
fun Route.validate(validator : Validator, build: Route.() -> Unit): Route {

    val newRoute = createChild(MySelector(1.0))
    newRoute.intercept(ApplicationCallPipeline.Features) {
        doSomething
    }
    newRoute.build()
    return newRoute
}
If i do this, it will run the intercep 1st and only after it will run the authentication
r

Rustam Siniukov

07/23/2021, 2:58 PM
Oh, sorry, you are right. I forgot that
Authentication
adds it’s own phase. You need a bit more code to make it work.
private val validationPhase = PipelinePhase("Validate")

fun Route.validate(validator : Validator, build: Route.() -> Unit): Route {
    val newRoute = createChild(MySelector())
    newRoute.insertPhaseAfter(ApplicationCallPipeline.Features, Authentication.ChallengePhase)
    newRoute.insertPhaseAfter(Authentication.ChallengePhase, validationPhase)
    newRoute.intercept(validationPhase) {
        doSomething
    }
    newRoute.build()
    return newRoute
}

class ValidationSelector: RouteSelector() {
  fun evaluate(context: RoutingResolveContext, segmentIndex: Int) = RouteSelectorEvaluation.Transparent
}
This way you make sure that your phase for validation will be after authentication phases. It’s a bit complicated and you need to know the internals of how phases work, that’s why we will implement simpler API in 2.0.0. You can follow it here https://youtrack.jetbrains.com/issue/KTOR-929
1
c

Carlos Santos

07/23/2021, 3:08 PM
it works, Thank you Rustam, it was really helpful! 👍
👍 1