例如,如果我有以下控制器:

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 "???";
    }
}


然后在我的服务器上运行它,然后我希望index方法返回http://my-server:8080

最佳答案

从Micronaut V1.2.0开始,您可以使用HttpHostResolver interface,例如:

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);
    }
}

10-06 08:10