在HTTP中,您可以定义一个accept
标头来指定要检索的内容:
curl --header "accept: text/plain" localhost:8080/greetings/
curl --header "accept: application/xml" localhost:8080/greetings/
我想知道,是否有针对micronaut的临时解决方案来解决这个问题。
有一篇博客文章(https://mrhaki.blogspot.com/2018/08/micronaut-mastery-return-response-based.html),描述了如何根据accept
标头产生不同的输出。但这对我来说并不对,因为micronaut中的大多数内容都是通过注释处理的。
我尝试使用@Consumes(MediaType.TEXT_PLAIN)
,但这仅适用于POST请求(这很明显,因为micronaut不会在GET请求中消耗数据)。 @Produces(MediaType.TEXT_PLAIN)
注释似乎设置了content type
标头并配置了输出编码,但似乎与路由没有交互。
@Produces(MediaType.APPLICATION_XML)
@Get("/")
String getXml() {
return "<greeting>Hello World</greeting>";
}
@Produces(MediaType.TEXT_PLAIN)
@Get("/")
String getPlaintext() {
return "Hello World";
}
虽然我希望这会将带有accept: text/plain
的HTTP请求路由到getPlaintext(),并将accept: application/xml
路由到getXml(),但它导致传入请求有2个匹配项:
DEBUG i.m.h.s.netty.RoutingInBoundHandler - Encoding emitted response object [More than 1 route matched the incoming request. The following routes matched /greetings/: GET - /greetings,GET - /greetings] using codec: io.micronaut.jackson.codec.JsonmediaTypeCodec@41ffaeb8
那么,有没有内置的解决方案根据HTTP accept
标头来路由HTTP请求?