The following example implements a simple echo server that echos the body sent in the request:
Using the @Body annotation
import io.micronaut.http.MutableHttpResponse
import io.micronaut.http.annotation.Body
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Post
import io.reactivex.Flowable
import io.reactivex.Single
@Post(value = "/echo", consumes = MediaType.TEXT_PLAIN) (1)
String echo(@Size(max = 1024) @Body String text) { (2)
}
Using the @Body annotation
Note that reading the request body is done in a non-blocking manner in that the request contents are read as the data becomes available and accumulated into the String passed to the method.
Using RxJava 2 to Read the request body
@Post(value = "/echo-flow", consumes = MediaType.TEXT_PLAIN) (1)
return text.collect(StringBuffer::new, StringBuffer::append) (3)
HttpResponse.ok(buffer.toString())
);
}
Using RxJava 2 to Read the request body
@Post(value = "/echo-flow", consumes = [MediaType.TEXT_PLAIN]) (1)
open fun echoFlow(@Body text: Flowable<String>): Single<MutableHttpResponse<String>> { (2)
return text.collect({ StringBuffer() }, { obj, str -> obj.append(str) }) (3)
.map { buffer -> HttpResponse.ok(buffer.toString()) }
}