Skip to content

Instantly share code, notes, and snippets.

@lmller
Last active November 23, 2018 08:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lmller/a13bfc8a21ead71991029c8cdfbd9899 to your computer and use it in GitHub Desktop.
Save lmller/a13bfc8a21ead71991029c8cdfbd9899 to your computer and use it in GitHub Desktop.
ktor fruit example
Gists for a blog post on blog.codecentric.de
dependencies {
...
implementation "io.ktor:ktor-auth:1.0.0"
}
repositories {
...
jcenter()
}
dependencies {
...
implementation "io.ktor:ktor-server-core:1.0.0"
implementation "io.ktor:ktor-server-netty:1.0.0"
}
fun Application.module() {
installGlobalFeatures()
val fruitStash = mutableListOf<Fruit>()
routing {
...
}
}
fun Application.installGlobalFeatures() {
install(ContentNegotiation) {...}
install(StatusPages) {...}
install(Authentication) {...}
}
dependencies {
...
implementation "io.ktor:ktor-jackson:1.0.0"
}
install(Authentication) {
basic {
validate { (name, password) ->
if(name == "lovis" && password == "cc hamburg") {
UserIdPrincipal(name)
} else {
null
}
}
}
}
...
authenticate {
post("/fruits") {
...
}
}
fun Application.module() {
install(feature = ContentNegotiation) {
jackson()
}
...
}
exception<IndexOutOfBoundsException> {
call.respond(NotFound, "404 Not Found")
}
fun Application.module() {
install(ContentNegotiation) {...}
install(StatusPages) {
exception<Throwable> { err -> call.respondText { err.message ?: "Unknown Error" } }
}
val fruitStash = mutableListOf<Fruit>()
routing {
...
get("/fruits/{index}") {
val index = call.parameters["index"]?.toIntOrNull()
if(index != null) {
val fruit = fruitStash[index]
call.respond(fruit)
} else {
call.respond(HttpStatusCode.NotFound)
}
}
}
}
fun Application.module() {
install(ContentNegotiation) {...}
val fruitStash = mutableListOf<Fruit>()
routing {
...
get("/fruits/{index}") {
val index = call.parameters["index"]?.toIntOrNull()
if(index != null) {
val fruit = fruitStash[index]
call.respond(fruit)
} else {
call.respond(HttpStatusCode.NotFound)
}
}
}
}
routing {
route("/fruits") {
authenticate {
post { ... }
}
get { ... }
get("/{index}") { ... }
}
}
fun Application.module() {
val fruitStash = mutableListOf<String>()
routing {
post("/fruits") {
fruitStash.add(call.receive<String>())
call.respond(HttpStatusCode.Created)
}
get("/fruits") {
call.respond(fruitStash)
}
}
}
fun main(args: Array<String>) {
embeddedServer(
factory = Netty,
port = 8080,
module = Application::module
).start(wait = true)
}
fun Application.module() {
routing {
...
}
}
data class Fruit(val name: String)
fun Application.module() {
val fruitStash = mutableListOf<Fruit>()
routing {
post("/fruits") {
fruitStash.add(call.receive<Fruit>())
call.respond(Created)
}
get("/fruits") {
call.respond(fruitStash)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment