I have a Ballerina package where there is a rest API and a listener defined in another module in the package. The package structure and the Ballerina code are as follows.
restapi % tree
.
├── Ballerina.toml
├── main.bal
└── modules
└── mod
├── Module.md
└── mod.bal
Ballerina.toml
[package]
org = "testorg"
name = "restapi"
version = "0.1.0"
distribution = "2201.8.2"
[build-options]
observabilityIncluded = true
main.bal
import ballerina/io;
public function main() {
io:println("Hello, World!");
}
mod.bal
import ballerina/http;
import ballerina/io;
listener http:Listener httpListener = new (8080);
string welcomeMessage = "Welcome!";
function init() returns error? {
io:println(welcomeMessage);
}
service / on httpListener {
resource function get greeting() returns string {
return "Hello, World!";
}
}
When I run the above package using bal run
, it runs and stops giving the following output. It seems the service does not work and it does not respond to the requests.
restapi % bal run
Compiling source
testorg/restapi:0.1.0
Running executable
Hello, World!
What should be done to make the service work?
We need to import the non-default module from the default module of the package to run the above service. To initialize a non-default module (run the init
function and handle the listeners), the non-default module needs to be imported by the default module of a Ballerina package. Since we are not using it for any other purpose in the default module other than that, we can import it using the import prefix _
.
Hence, the main.bal
file needs to be edited as follows.
import ballerina/io;
import restapi.mod as _;
public function main() {
io:println("Hello, World!");
}
It will now run the service and give the output.
restapi % bal run
Compiling source
testorg/restapi:0.1.0
Running executable
Welcome!
Hello, World!