Ktor Architecture & Lifecycle

Architecture

a75ce66dd598d66738b87023e85a44b7.png

Ktor Routes

accept(ContextType.Text.Plain) { ... }
accept(ContextType.Text.Html) { ... }
accept(ContextType.Application.Json) { ... }

Builder Functions

    routing {
		
        route("/weather") {
            route("/asia") {
                // this will only execute if the specified systemtoken is present
                header("systemtoken", "weathersystem") {
                    handle {
                        call.respondText("The weather is sunny")
                    }
                }
            }
            route("/europe", HttpMethod.Get) {
                // if the parameter name is not present call the other handle function
                param("name") {
                    handle {
                        var name = call.parameters.get("name")
                        call.respondText("The weather is $name")
                    }
                }
                handle {
                    call.respondText("The weather is rainy")
                }
            }
            route("/usa") {
                get {
                    call.respondText("The weather is rainy")
                }
            }
        }
	}

Sample Request: curl -H "systemtoken: weathersystem" -X GET "localhost:8080/weather/asia"

Calling 3rd Party REST Services

val client = HttpClient(Apache) {
	install(JsonFeature) {
		serializer = GsonSerializer()
	}
}

Testing with the MockEngine

val client = HttpClient(MockEngine) 
{
	engine {
		addHandler { request ->
			when (request.url.fullUrl) {
				"https://example.org/" -> {
					val responseHeaders = headersOf("Content-Type" to lostOf(ContentType.Text.Plain.toString()))
					respond("Hello, world", headers = responseHeaders)
				}
				else -> error("Unhandled ${request.url.fullUrl}")
			}
		}
	}
}

Revision #1
Created 17 April 2022 00:03:34 by Elkip
Updated 17 April 2022 01:02:09 by Elkip