netty 4.1: improve request uri parsing
@@ -16,8 +16,12 @@ import io.opentracing.propagation.Format;
import io.opentracing.tag.Tags;
import io.opentracing.util.GlobalTracer;
import java.net.InetSocketAddress;
+import java.net.URI;
+import java.net.URISyntaxException;
import java.util.Collections;
+import lombok.extern.slf4j.Slf4j;
+@Slf4j
public class HttpClientRequestTracingHandler extends ChannelOutboundHandlerAdapter {
@Override
@@ -37,10 +41,6 @@ public class HttpClientRequestTracingHandler extends ChannelOutboundHandlerAdapt
final HttpRequest request = (HttpRequest) msg;
final InetSocketAddress remoteAddress = (InetSocketAddress) ctx.channel().remoteAddress();
- String url = request.uri();
- if (request.headers().contains(HOST)) {
- url = "http://" + request.headers().get(HOST) + url;
- }
final Span span =
GlobalTracer.get()
.buildSpan("netty.client.request")
@@ -48,7 +48,7 @@ public class HttpClientRequestTracingHandler extends ChannelOutboundHandlerAdapt
.withTag(Tags.PEER_HOSTNAME.getKey(), remoteAddress.getHostName())
.withTag(Tags.PEER_PORT.getKey(), remoteAddress.getPort())
.withTag(Tags.HTTP_METHOD.getKey(), request.method().name())
- .withTag(Tags.HTTP_URL.getKey(), url)
+ .withTag(Tags.HTTP_URL.getKey(), formatUrl(request))
.withTag(Tags.COMPONENT.getKey(), "netty-client")
.withTag(DDTags.SPAN_TYPE, DDSpanTypes.HTTP_CLIENT)
.start();
@@ -72,4 +72,18 @@ public class HttpClientRequestTracingHandler extends ChannelOutboundHandlerAdapt
scope.close();
}
}
+
+ private String formatUrl(final HttpRequest request) {
+ try {
+ URI uri = new URI(request.uri());
+ if ((uri.getHost() == null || uri.getHost().equals("")) && request.headers().contains(HOST)) {
+ uri = new URI("http://" + request.headers().get(HOST) + request.uri());
+ }
+ return new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), uri.getPath(), null, null)
+ .toString();
+ } catch (final URISyntaxException e) {
+ log.debug("Cannot parse netty uri: {}", request.uri());
+ return request.uri();
+ }
+ }
}
