如何在 Ballerina 中的 http 资源函数中返回流值?

问题描述 投票:0回答:1

我正在将 csv 文件中的设置值作为记录流读取。我不想将它们转换为记录数组,而是像在 http 响应中那样发送流。我怎样才能实现这个目标?

mime-types mime ballerina ballerina-swan-lake ballerina-http
1个回答
0
投票

Ballerina 仅支持在 http 资源中返回

anydata
类型的子类型。但您可以使用
http:Caller
对象将流添加为响应中的
mime:Entity
正文部分。

假设您在资源文件夹中有这样的 csv 文件,

name,department
Jo,IT
Jane,IT
Jim,Sales
Kim,Marketing

您可以在服务中定义http资源,如下所示,

import ballerina/http;
import ballerina/io;
import ballerina/mime;

string[] arr = [];

type Employee record {|
    string name;
    string department;
|};

service /api on new http:Listener(8080) {

    resource function get employeesAsMime(http:Caller caller) returns error? {
        stream<Employee, io:Error?> employees = check getEmployees();
        stream<byte[], io:Error?> payload = stream from var employee in employees
            select employee.toString().toBytes();
        mime:Entity entity = new;
        entity.setContentId("employee-stream");
        entity.setBody(payload);
        http:Response response = new;
        response.setBodyParts([entity]);
        check caller->respond(response);
    }
}

function getEmployees() returns stream<Employee, io:Error?>|io:Error {
    return io:fileReadCsvAsStream("./resources/employees.csv");
}

并且使用

http:Client
您可以按如下方式使用此流,

import ballerina/io;
import ballerina/http;
import ballerina/mime;

public function main() returns error? {
    http:Client cl = check new ("http://localhost:8080");

    http:Response mimeResponse = check cl->/api/employeesAsMime();
    mime:Entity[] bodyParts = check mimeResponse.getBodyParts();
    foreach mime:Entity bodyPart in bodyParts {
        if bodyPart.getContentId() == "employee-stream" {
            stream<byte[], io:Error?> byteArrayStream = check bodyPart.getByteStream();
            check from var byteArray in byteArrayStream
            do {
                io:println(string:fromBytes(byteArray));
            };
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.