6 The HTTP Server
Using the CLI If you create your project using the Micronaut CLI |
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 to be consumed by HTTP clients, regardless of the language they are written in. To use the HTTP server you need the http-server-netty
dependency in your build:
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 responds to a GET requests to /hello and returns a response with a text/plain content type |
3 | By defining a method named index , by convention the method is exposed via the /hello URI |