微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

来自发布者的 Reactor-netty http 状态

如何解决来自发布者的 Reactor-netty http 状态

我不确定如何解决这个问题, http 响应状态取决于我需要阅读的正文。 所以我有类似的东西:

private NettyOutbound handleRequest(HttpServerRequest req,HttpServerResponse res) {
    Mono<String> body = req.receive().aggregate().asstring(UTF_8);
    ...
    return res.status(status)
                .sendString(body,UTF_8);
}

private int status(String body) {
    ...
}

但是为了获得我需要阅读正文的状态,我没有看到任何使用发布者提供的值的选项。我怎样才能做到这样我就可以调用上面的 status 方法并在创建 NettyOutbound

时使用该状态

解决方法

如果我理解正确,您正在尝试实现路由处理程序

我认为以下应该有效

package hello;

import reactor.core.publisher.Mono;
import reactor.netty.DisposableServer;
import reactor.netty.http.server.HttpServer;
import reactor.netty.http.server.HttpServerRequest;
import reactor.netty.http.server.HttpServerResponse;

public class Application {
    
    private Mono<Void> handleRequest(HttpServerRequest req,HttpServerResponse res) {
        return req.receive().aggregate().asString().flatMap(body ->
                {
                    int status = status(body);
                    return res.status(status).sendString(Mono.just(body)).then();
                }
        );
    }

    private int status(String body) {
        return body.toLowerCase().equals("hello") ? 200 : 400;
    }

    public void startServer() {
        DisposableServer server =
                HttpServer.create()
                        .host("localhost")
                        .port(8080)
                        .route(routes -> routes.get("/hello",this::handleRequest))
                        .bindNow();
        
        server.onDispose().block();
    }

    public static void main(String[] args) {
        new Application().startServer();
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。