Using a top-level function for a handler in Kotlin
To create a handler in Kotlin, you can set a top-level function
Here is an example of a handler that accepts a number and returns it:
fun handle(s: Int): Int = s
Warning
For top-level functions, provide only one parameter.
You can test the function from the above example in the following ways:
-
In the management console
, on the Testing tab of the function page. -
Using the following HTTPS request with the ?integration=raw parameter:
curl \ --header "Authorization: Bearer <IAM_token>" \ --data "<number>" \ "https://functions.yandexcloud.net/<function_ID>?integration=raw"In the
--dataparameter, specify the function’s return value.
Examples
Processing an HTTP request
The script below processes an incoming HTTP request and outputs the results: the HTTP status code and the response body.
Handler.kt:
data class Request(
val httpMethod: String?,
val headers: Map<String, String> = mapOf(),
val body: String = ""
)
data class Response(
val statusCode: Int,
val body: String
)
fun handle(request: Request): Response {
return Response(200, "Hello World!")
}
The result format depends on whether the user provided ?integration=raw in the request:
-
If
?integration=rawwas provided:{ "statusCode": 200, "body": "Hello World!" } -
If
?integration=rawwas not provided:"Hello World!"The
200code will be returned not as part of the response body, as with the?integration=rawparameter, but as the HTTP status code.
HTTP request structure output
The script below processes an incoming HTTP request and outputs its structure and the HTTP status code.
Handler.kt:
data class Response(
val statusCode: Int,
val body: String
)
fun handle(request: String): Response {
return Response(200, request)
}