Skip to content

Instantly share code, notes, and snippets.

@xbkaishui
Created October 30, 2021 01:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xbkaishui/49a052a017ee8441e7a6833a65874123 to your computer and use it in GitHub Desktop.
Save xbkaishui/49a052a017ee8441e7a6833a65874123 to your computer and use it in GitHub Desktop.
grpc-host-intercepter
public class ClientHostInterceptor implements ClientInterceptor {
private String host;
private static Metadata.Key<String> HOST_HEADER =
Metadata.Key.of("Host", Metadata.ASCII_STRING_MARSHALLER);
public ClientHostInterceptor(final String host) {
this.host = host;
}
public String getHost() {
return host;
}
public void setHost(final String host) {
this.host = host;
}
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(final MethodDescriptor<ReqT, RespT> method,
final CallOptions callOptions, final Channel next) {
log.info("Intercepted " + method.getFullMethodName());
ClientCall<ReqT, RespT> call = next.newCall(method, callOptions);
call = new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(call) {
@Override
public void start(Listener<RespT> responseListener, Metadata headers) {
if (StringUtils.isNotEmpty(host)) {
log.info("Attaching host header. {}", host);
headers.put(HOST_HEADER, host);
}
super.start(responseListener, headers);
}
};
return call;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment