How to dynamically change resource URL path in Ballerina?

49 Views Asked by At

Is it possible to change the resource url of a Ballerina service dynamically.

For an example,

resource isolated function get <DYNAMIC_CONTEXT>/[string resourcePath]() {
    //;
}

In above code, can we set the <DYNAMIC_CONTEXT> dynamically?

My actual objective here is to define this <DYNAMIC_CONTEXT> from the Config.toml or similar manner. So EoD, we are capable of configuring the <DYNAMIC_CONTEXT> on deployment of the service. The end user always has to follow that specific context path which is fixed from their end of view.

1

There are 1 best solutions below

0
On BEST ANSWER

The easiest way is to define the <DYNAMIC_CONTEXT> as a path parameter and, to use a configurable variable (which we can use to provide it's value at the runtime) as shown below.

import ballerina/http;

const PORT = 9090;
configurable string dynamicContext = ?;

service / on new http:Listener(PORT) {
    resource function get [string dynamicContext]/[string resourcePath1] () returns error? {
        // Do something
    }
}

If you want to change the base path dynamically, you can use listener lifecycle method to attach. The service can be defined as either a class declaration or a constructor expression. When attaching the service to the listener, the attach() method can take a variable as the base path which is the second argument.

import ballerina/http;

const PORT = 9090;
configurable string dynamicContext = ?;
listener http:Listener hl = new(9090);

public function main() returns error? {
    check hl.attach(mockService, dynamicContext);
}

http:Service mockService = service object {
    resource function get [string resourcePath1] () returns string {
        return "Mock invoked!";
    }
};