Search code examples
javaweb-servicesmicronaut

How does a Micronaut controller determine its base URL


For example if I have the following controller:

import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.*;

@Controller("/test")
public class TestController {
    @Get()
    @Produces(MediaType.TEXT_PLAIN)
    public String index() {
        // How should this be implemented?
        return "???";
    }
}

and I run it on my-server, then I would like the index method to return http://my-server:8080.


Solution

  • Asof Micronaut V1.2.0, you can use the HttpHostResolver interface, for example:

    import io.micronaut.http.*;
    import io.micronaut.http.annotation.*;
    import io.micronaut.http.server.util.HttpHostResolver;
    import io.micronaut.web.router.RouteBuilder;
    
    @Controller("/test")
    public class TestController {
        private final HttpHostResolver httpHostResolver;
        private final RouteBuilder.UriNamingStrategy uriNamingStrategy;
    
        public TestController(
                HttpHostResolver httpHostResolver,
                RouteBuilder.UriNamingStrategy uriNamingStrategy
        ) {
            this.httpHostResolver = httpHostResolver;
            this.uriNamingStrategy = uriNamingStrategy;
        }
    
        @Get()
        @Produces(MediaType.TEXT_PLAIN)
        public String index(HttpRequest httpRequest) {
            return httpHostResolver.resolve(httpRequest) +
                    uriNamingStrategy.resolveUri(TestController.class);
        }
    }