private static HttpHeaders initHeaders(HttpServerRequest channel) { NettyHeadersAdapter headersMap = new NettyHeadersAdapter(channel.requestHeaders()); return new HttpHeaders(headersMap); }
@Override public String getMethodValue() { return this.request.method().name(); }
private static String resolveRequestUri(HttpServerRequest request) { String uri = request.uri(); for (int i = 0; i < uri.length(); i++) { char c = uri.charAt(i); if (c == '/' || c == '?' || c == '#') { break; } if (c == ':' && (i + 2 < uri.length())) { if (uri.charAt(i + 1) == '/' && uri.charAt(i + 2) == '/') { for (int j = i + 3; j < uri.length(); j++) { c = uri.charAt(j); if (c == '/' || c == '?' || c == '#') { return uri.substring(j); } } return ""; } } } return uri; }
private static URI resolveBaseUrl(HttpServerRequest request) throws URISyntaxException { String scheme = getScheme(request); String header = request.requestHeaders().get(HttpHeaderNames.HOST); if (header != null) { final int portIndex; if (header.startsWith("[")) { portIndex = header.indexOf(':', header.indexOf(']')); } else { portIndex = header.indexOf(':'); } if (portIndex != -1) { try { return new URI(scheme, null, header.substring(0, portIndex), Integer.parseInt(header.substring(portIndex + 1)), null, null, null); } catch (NumberFormatException ex) { throw new URISyntaxException(header, "Unable to parse port", portIndex); } } else { return new URI(scheme, header, null, null); } } else { InetSocketAddress localAddress = request.hostAddress(); return new URI(scheme, null, localAddress.getHostString(), localAddress.getPort(), null, null, null); } }
@Override public Publisher<Void> apply(HttpServerRequest httpRequest, HttpServerResponse httpResponse) { LOGGER.debug( "Accepted request: {}, headers: {}, params: {}", httpRequest, httpRequest.requestHeaders(), httpRequest.params()); if (httpRequest.method() != POST) { LOGGER.error("Unsupported HTTP method. Expected POST, actual {}", httpRequest.method()); return methodNotAllowed(httpResponse); } return httpRequest .receive() .aggregate() .map(ByteBuf::retain) .doOnNext(content -> metrics.markRequest()) .flatMap(content -> handleRequest(content, httpRequest, httpResponse)) .doOnSuccess(avoid -> metrics.markResponse()) .onErrorResume(t -> error(httpResponse, ExceptionProcessor.toMessage(t))); }
/** * Listen for WebSocket with the given route predicate to invoke the matching handlers * * @param condition a predicate given each inbound request * @param handler an handler to invoke for the given condition * @param protocols sub-protocol to use in WS handshake signature * * @return a new handler */ @SuppressWarnings("unchecked") default HttpServerRoutes ws(Predicate<? super HttpServerRequest> condition, BiFunction<? super WebsocketInbound, ? super WebsocketOutbound, ? extends Publisher<Void>> handler, @Nullable String protocols, int maxFramePayloadLength) { return route(condition, (req, resp) -> { if (req.requestHeaders() .contains(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE, true)) { HttpServerOperations ops = (HttpServerOperations) req; return ops.withWebsocketSupport(req.uri(), protocols, maxFramePayloadLength, handler); } return resp.sendNotFound(); }); }
@Override public Flux<DataBuffer> getBody() { return this.request.receive().retain().map(this.bufferFactory::wrap); }
BiFunction<? super HttpServerRequest, ? super HttpServerResponse, ? extends Publisher<Void>> postHandler() { return (req, resp) -> { req.requestHeaders() .entries() .forEach(entry -> System.out.println(String.format("header [%s=>%s]", entry.getKey(), entry.getValue()))); return resp.sendString(req.receive() .take(1) .log("received") .flatMap(data -> { final StringBuilder response = new StringBuilder().append("hello ") .append(data.readCharSequence( data.readableBytes(), Charset.defaultCharset())); System.out.println(String.format( "%s from thread %s", response.toString(), Thread.currentThread())); return Flux.just(response.toString()); })); }; }
BiFunction<? super HttpServerRequest, ? super HttpServerResponse, ? extends Publisher<Void>> getHandler() { return (req, resp) -> { req.requestHeaders() .entries() .forEach(entry1 -> System.out.println(String.format("header [%s=>%s]", entry1.getKey(), entry1.getValue()))); req.params() .entrySet() .forEach(entry2 -> System.out.println(String.format("params [%s=>%s]", entry2.getKey(), entry2.getValue()))); StringBuilder response = new StringBuilder().append("hello ") .append(req.params() .get("name")); System.out.println(String.format("%s from thread %s", response.toString(), Thread.currentThread())); return resp.sendString(Flux.just(response.toString())); }; }
@Test public void forwardedAllDirectives() { testClientRequest( clientRequestHeaders -> clientRequestHeaders.add("Forwarded", "host=a.example.com:443;proto=https"), serverRequest -> { Assertions.assertThat(serverRequest.hostAddress().getHostString()).isEqualTo("a.example.com"); Assertions.assertThat(serverRequest.hostAddress().getPort()).isEqualTo(443); Assertions.assertThat(serverRequest.scheme()).isEqualTo("https"); }); }
private Mono<Void> proxy(HttpServerRequest request, HttpServerResponse response) { return HttpClient.create() .wiretap(true) .headers(h -> h.add(filterRequestHeaders(request.requestHeaders()))) .get() .uri(URI.create("http://localhost:" + CONTENT_SERVER_PORT + "/" + request.path()) .toString()) .response((targetResponse, buf) -> response.headers(filterResponseHeaders(targetResponse.responseHeaders())) .send(buf.retain()) .then()) .then(); }
.port(0) .route(r -> r.get("/test/{param}", (req, res) -> { System.out.println(req.requestHeaders().get("test")); return res.header("content-type", "text/plain") .sendWebsocket((in, out) -> .publishOn(Schedulers.single()) .doOnNext(s -> serverRes.incrementAndGet()) .map(it -> it + ' ' + req.param("param") + '!') .log("server-reply"))); }))
@Test public void forwardedForIp() { testClientRequest( clientRequestHeaders -> clientRequestHeaders.add("Forwarded", "for=192.0.2.60;proto=http;by=203.0.113.43"), serverRequest -> { Assertions.assertThat(serverRequest.remoteAddress().getHostString()).isEqualTo("192.0.2.60"); Assertions.assertThat(serverRequest.remoteAddress().getPort()).isPositive(); Assertions.assertThat(serverRequest.scheme()).isEqualTo("http"); }); }
@Test public void xForwardedForHostAndPort() { testClientRequest( clientRequestHeaders -> { clientRequestHeaders.add("X-Forwarded-For", "192.168.0.1"); clientRequestHeaders.add("X-Forwarded-Host", "a.example.com"); clientRequestHeaders.add("X-Forwarded-Port", "8080"); }, serverRequest -> { Assertions.assertThat(serverRequest.remoteAddress().getHostString()).isEqualTo("192.168.0.1") ; Assertions.assertThat(serverRequest.hostAddress().getHostString()).isEqualTo("a.example.com"); Assertions.assertThat(serverRequest.hostAddress().getPort()).isEqualTo(8080); }); }
@Override public InetSocketAddress getRemoteAddress() { return this.request.remoteAddress(); }
@Test public void xForwardedHostAndPort() { testClientRequest( clientRequestHeaders -> { clientRequestHeaders.add("X-Forwarded-Host", "192.168.0.1"); clientRequestHeaders.add("X-Forwarded-Port", "8080"); }, serverRequest -> { Assertions.assertThat(serverRequest.hostAddress().getHostString()).isEqualTo("192.168.0.1"); Assertions.assertThat(serverRequest.hostAddress().getPort()).isEqualTo(8080); }); }
@Override protected MultiValueMap<String, HttpCookie> initCookies() { MultiValueMap<String, HttpCookie> cookies = new LinkedMultiValueMap<>(); for (CharSequence name : this.request.cookies().keySet()) { for (Cookie cookie : this.request.cookies().get(name)) { HttpCookie httpCookie = new HttpCookie(name.toString(), cookie.value()); cookies.add(name.toString(), httpCookie); } } return cookies; }