Created
April 16, 2019 07:09
-
-
Save pubudu91/98eb9a8d7782846d53a3ab75095a5ff2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Top. 🔝
Thanks for your help @pubudu91
You are awesome