Heshan Sudarshana
Heshan Sudarshana

Reputation: 151

Filter request/response from the listener level in Ballerina Swan Lake

In Ballerina 1.2.x versions, it was possible to filter request/response at the listener level. This allowed filtering of requests and responses for multiple services using the same listener.

However, in Ballerina Swan Lake, I couldn't find a similar capability. It seems like Interceptor is the equivalent of Filter in the newer versions, but I couldn't find a way to engage it at the listener level—it appears to be limited to the service level.

Is there a way to engage an interceptor at the listener level, or is there an alternative solution?

Upvotes: 0

Views: 33

Answers (1)

The Interceptors are designed to be engaged at service level. If you want to engage a common interceptor for all the services attached to a particular listener, then you need to add the common interceptor in all of the services.

import ballerina/http;
import ballerina/log;

service class CommonInterceptor {
    *http:RequestInterceptor;

    resource function 'default [string... path](http:RequestContext ctx) returns http:NextService|error? {
        log:printInfo("Received request", path = string:'join("/", ...path));
        return ctx.next();
    }
}

listener http:Listener httpListener = new (9090);

service http:InterceptableService /v1 on httpListener {

    public function createInterceptors() returns CommonInterceptor {
        return new;
    }

    resource function 'default [string... path]() returns string {
        return "Hello, World from v1!";
    }
}

service http:InterceptableService /v2 on httpListener {

    public function createInterceptors() returns CommonInterceptor {
        return new;
    }

    resource function 'default [string... path]() returns string {
        return "Hello, World from v2!";
    }
}

Upvotes: 1

Related Questions