Skip to content

Instantly share code, notes, and snippets.

@pubudu91
Created April 16, 2019 07:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pubudu91/98eb9a8d7782846d53a3ab75095a5ff2 to your computer and use it in GitHub Desktop.
Save pubudu91/98eb9a8d7782846d53a3ab75095a5ff2 to your computer and use it in GitHub Desktop.
import ballerina/http;
import ballerina/log;
// Data is formatted as: key1=val1;key2=val2
type Person record {|
string name = "";
int age = 0;
|};
listener http:Listener endpoint = new (3000);
@http:ServiceConfig {
basePath: "/api"
}
service Logger on endpoint {
@http:ResourceConfig{
path: "/logger",
methods: ["POST"]
}
resource function GetTextPayload(http:Caller caller, http:Request req) {
var payload = req.getTextPayload();
if (payload is string) {
Person|error p = toRecord(payload);
if (p is Person) {
// Now you can access the fields as p.name, p.age etc.
string name = p.name;
int age = p.age;
var result = caller->respond("Payload received");
return;
} else {
var result = caller->respond(get400Response(p.reason()));
return;
}
} else {
var result = caller->respond(get400Response(payload.reason()));
}
}
}
function toRecord(string data) returns Person|error {
Person p = {};
string[] fields = data.split(";");
foreach var field in fields {
string[] keyVal = field.split("=");
match keyVal[0] {
"name" => p.name = keyVal[1];
"age" => p.age = check int.convert(keyVal[1]);
var invalidField => {
error e = error("Invalid field: " + invalidField);
return e;
}
}
}
return p;
}
function get400Response(string msg) returns http:Response {
http:Response err400 = new;
err400.statusCode = 400;
err400.setPayload(untaint msg);
return err400;
}
@JoseCage
Copy link

Top. 🔝

Thanks for your help @pubudu91
You are awesome

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment