3

我的教授希望我写一个关于如何部署 Ballerina 服务的小教程。所以我正在努力学习它。我正在使用 1.2 版,我对污点检查的概念和变量类型有点不知所措......

我正在尝试编写一个最小的 REST 服务,其端点从另一个 api 请求 json 数据,然后使用该 JSON 来做事。

到目前为止的工作如下:

service tutorial on new http:Listener(9090) {

    // Resource functions are invoked with the HTTP caller and the incoming request as arguments.
    resource function getName(http:Caller caller, http:Request req) {
   http:Client clientEP = new("https://api.scryfall.com/");

    var resp = clientEP->get("/cards/random");
    if (resp is http:Response) {

        var payload = resp.getJsonPayload();

        if (payload is json) {

            var result = caller->respond(<@untainted>(payload));
        } else {

            log:printError("");
        }
    } else {

        log:printError("");
    }
}

响应从https://api.scryfall.com/cards/random返回的 JSON

但是现在让我们说,我想从该 JSON 中访问单个值。例如“名称”。如果我尝试像这样访问它:payload["name"]

我得到:无效操作:类型'json'不支持索引

我刚刚发现,如果我先像这样创建地图,它会起作用:

地图 mp = <地图>有效载荷;

如果我然后访问 mp["name"] 它可以工作。但为什么?如果您仍然必须创建地图然后投射有效负载,那么 json 类型有什么好处?我将如何访问 json 中的 json?例如 mp["data"][0]... 无效操作:类型 'json' 不再支持索引...

而且我仍在尝试理解污点检查的概念......我是否只是在检查内容后将所有被污染的东西都投射到 <@untainted> ?有时我真的不明白文档试图告诉我什么......

4

1 回答 1

3

我建议您使用 Ballerina Swan Lake 版本。Swan Lake 版本包含对各种语言功能的增强。这是涵盖您的用例的示例代码。您可以在https://ballerina.io/下载 Swan Lake Alpha2

import ballerina/io;
import ballerina/http;

service tutorial on new http:Listener(9090) {
    resource function get payload() returns json|error {
        http:Client clientEP = check new ("https://api.scryfall.com/");
        json payload = <json> check clientEP -> get("/cards/random", targetType = json);

        // Processing the json payload 
        // Here the type of the `payload.name` expression is json | error
        // You can eliminate with check: it returns from this resource with this error
        json nameField = check payload.name;
        io:println(nameField);

        // You can traverse the json tree as follows
        json standardLegality = check payload.legalities.standard;
        io:println(standardLegality);

        // colors is an array 
        // The cast is necessary because `check payload.colors` gives you a json
        json colors = <json[]> check payload.colors;
        io:println(colors);

        // Responding with the complete payload recived from api.scryfall.com
        return payload;
    }
}

污点分析可帮助您编写没有安全漏洞的代码。但是,我们在 Swan Lake 版本中禁用了污点分析。如果要启用它,可以使用该--taint-check选项bal build

于 2021-02-24T20:51:59.300 回答