Micronaut 控制器如何确定其基数 URL

How does a Micronaut controller determine its base URL

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

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

并且我 运行 它在我的服务器上,然后我希望索引方法 return http://my-server:8080.

这似乎有效:

import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.*;
import io.micronaut.runtime.server.EmbeddedServer;
import io.micronaut.web.router.RouteBuilder;

import java.net.*;

@Controller("/test")
public class TestController {
    protected final String baseUrl;

    public TestController(EmbeddedServer embeddedServer, RouteBuilder.UriNamingStrategy uns)
            throws MalformedURLException {
        final String host = embeddedServer.getHost();
        final int port = embeddedServer.getPort();
        final String file = uns.resolveUri(TestController.class);
        baseUrl = new URL("http", host, port, file).toString();
    }

    @Get()
    @Produces(MediaType.TEXT_PLAIN)
    public String index() {
        return baseUrl;
    }
}

我不确定它是否符合习惯,或者它是否适用于所有情况。如果有人发布更好的答案,我会接受。

如果您希望控制器在 / 时响应,请使用 @Controller("/") 而不是 @Controller("/test")

Asof 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);
    }
}
package com.tech.api;

import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.PathVariable;
import java.util.List;
import javax.inject.Inject;

@Controller("/")
public class ModelDefinitionsApi {

    @Get(uri="/modelName", produces = MediaType.APPLICATION_JSON)
    public String getModel(@PathVariable String modelName) {
        return "modelName";
    }
}

http://my-server:8080 => 主控制器url

http://my-server:8080/modelName => 对于 getModel 方法