- getStatusCode
- setStatusCode
The example below shows how getStatusCode method can be used to make invocation time decisions on an endpoint’s availability and act accordingly. Similarly, you can utilize received status codes of HTTP endpoints as an effective way of hardening your program when it’s appropriate.
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
package statuscode.sample; | |
import ballerina.net.http; | |
import ballerina.lang.system; | |
import ballerina.lang.messages; | |
import ballerina.lang.jsons; | |
import ballerina.lang.strings; | |
@http:BasePath {value:"/proxy"} | |
service ProxyService { | |
http:ClientConnector backend = create http:ClientConnector("http://localhost:9090"); | |
message request = {}; | |
json payload = `{"status":"PLACEHOLDER"}`; | |
@http:GET{} | |
resource proxyresource (message m) { | |
try{ | |
string controlHeader= messages:getHeader(m,"CONTROLLER"); | |
if (controlHeader == "faulty backend") | |
{ | |
request = http:ClientConnector.get(backend, "/faultybackend", m); | |
int statusCode = http:getStatusCode(request); | |
if (statusCode > 499){ | |
jsons:set(payload,"$.status","something went wrong with the backend service. status code: "+strings:valueOf(statusCode)); | |
messages:setJsonPayload(request,payload); | |
} | |
} | |
else | |
{ | |
request = http:ClientConnector.get(backend, "/backend", m); | |
} | |
reply request; | |
} catch (exception e){ | |
system:log(3,"it is but a scratch!"); | |
} | |
} | |
} |
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
package statuscode.sample; | |
import ballerina.lang.messages; | |
import ballerina.net.http; | |
import ballerina.lang.system; | |
@http:BasePath {value:"/backend"} | |
service BackendService { | |
message response = {}; | |
json payload = `{"status":"all good"}`; | |
@http:GET{} | |
resource backendresource (message m) { | |
try{ | |
messages:setJsonPayload(response, payload); | |
reply response; | |
} catch (exception e){ | |
system:log(3,"it is but a scratch!"); | |
} | |
} | |
} |
curl -X GET -v http://localhost:9090/proxy -H "CONTROLLER: faulty backend"
find out more about ballerina here: http://ballerinalang.org
Note: this example was written for ballerina 0.86 and may not work with other versions.
No comments:
Post a Comment