6 The HTTP Server
Using the CLI If you are creating your project using the Micronaut CLI’s |
Micronaut includes both non-blocking HTTP server and client APIs based on Netty.
The design of the HTTP server in Micronaut is optimized for interchanging messages between Microservices, typically in JSON, and is not intended as a full server-side MVC framework. For example, there is currently no support for server-side views or features typical of a traditional server-side MVC framework.
The goal of the HTTP server is to make it as easy as possible to expose APIs that can be consumed by HTTP clients, whatever language they may be written in. To use the HTTP server you must have the http-server-netty
dependency on your classpath.
implementation("io.micronaut:micronaut-http-server-netty")
<dependency>
<groupId>io.micronaut</groupId>
<artifactId>micronaut-http-server-netty</artifactId>
</dependency>
A “Hello World” server application can be seen below:
import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
@Controller("/hello") (1)
public class HelloController {
@Get(produces = MediaType.TEXT_PLAIN) (2)
public String index() {
return "Hello World"; (3)
}
}
import io.micronaut.http.MediaType
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
@Controller('/hello') (1)
class HelloController {
@Get(produces = MediaType.TEXT_PLAIN) (2)
String index() {
'Hello World' (3)
}
}
import io.micronaut.http.MediaType
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
@Controller("/hello") (1)
class HelloController {
@Get(produces = [MediaType.TEXT_PLAIN]) (2)
fun index(): String {
return "Hello World" (3)
}
}
1 | The class is defined as a controller with the @Controller annotation mapped to the path /hello |
2 | The method will respond to a GET request to /hello and returns a response with a text/plain content type |
3 | By defining method called index , by convention the method is exposed via the /hello URI |