ballerina-platform / ballerina-library

The Ballerina Library
https://ballerina.io/learn/api-docs/ballerina/
Apache License 2.0
136 stars 64 forks source link

HTTP header propagation #2680

Open shafreenAnfar opened 2 years ago

shafreenAnfar commented 2 years ago

HTTP header propagation from one service to another is a common requirement in microservices deployments. Most importantly this is needed to enable distributed tracing.

Following is how you can achieve this requirement using Feign (Spring Boot). It uses request interceptors for this. Just adding the below interceptor would make sure all the outbound requests would include all the inbound request headers which starts with x-.

@Component
public class PropagateHeadersInterceptor implements RequestInterceptor {

    private @Autowired HttpServletRequest request;

    public void apply(RequestTemplate template) {
        try
        {
            Enumeration<String> e = request.getHeaderNames();
            while (e.hasMoreElements())
            {
                String header = e.nextElement();
                if (header.startsWith("x-"))
                {
                    String value = request.getHeader(header);
                    template.header(header, value);
                }
            }
        }
        catch (IllegalStateException e) {}
    }
}
shafreenAnfar commented 2 years ago

At the moment this is a bit hectic in Ballerina because you need to pass around the inbound request headers all the way to the http:Client action. Doing so also sort of get mixed with business logic, which reduces the readability of the code.