Configurability enables users to modify the system behavior through external user inputs. Ballerina Language provides an in-built functionality to configure values at runtime through configurable module-level variables.
Consider the following step-by-step guide to configuring a Ballerina package that contains an HTTP service.
Create a Ballerina package using the following command.
bal new greetings
Replace the content of the file
main.balwith the following.
Here, we created a Ballerina package named
greetingsthat contains configurable variables
greetingwith respective types
Greeting. These variables are used in the HTTP service where the resource function
greeting()provides a configured message.
portis initialized with a default value
9090, which indicates that the configuration is optional. This value will be used for the variable initialization in case the configuration value will not be provided by the user at the runtime.
greetingis initialized with the
?syntax, which indicates that providing a configuration value is mandatory. Therefore, the program will finish the execution abruptly with a runtime exception, if the value is not provided at the runtime.
To provide the values for
greetingthrough a configuration file, create a file named
Config.tomlwith the following content in the package root directory.
Execute the following command to build and execute the program.
The output will be as follows.
Compiling source sample/greetings:0.1.0 Running executable
This will start the HTTP service on the configured endpoint
To verify the configuration, execute the following command.
curl http://localhost:8080/greeting -X POST
The response will be similar to the following.
Hello Tom! Good Morning!