【问题标题】:Reactor-netty http status from publisher来自发布者的 Reactor-netty http 状态
【发布时间】:2021-05-03 13:07:39
【问题描述】:

我不确定如何处理这个问题, 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 时使用该状态

【问题讨论】:

    标签: reactor-netty


    【解决方案1】:

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

    我认为以下应该可行

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-05
      • 1970-01-01
      • 1970-01-01
      • 2017-10-02
      • 1970-01-01
      • 2013-08-24
      相关资源
      最近更新 更多