Back to Examples

HTTP service - Chunking

The HTTP service can be configured for chunked responses. By default, the HTTP service sends messages with the content-length header. If the message size is larger than the buffer size (8K), messages are chunked. Chunking can be disabled using the @http:ServiceConfig. The chunking behavior can be configured as CHUNKING_AUTO, CHUNKING_ALWAYS, or CHUNKING_NEVER only available HTTP/1.1 protocol. When the config is set to CHUNKING_ALWAYS, chunking happens irrespective of the response payload size.

import ballerina/http;

type Album readonly & record {|
    string title;
    string artist;
|};

table<Album> key(title) albums = table [
    {title: "Blue Train", artist: "John Coltrane"},
    {title: "Jeru", artist: "Gerry Mulligan"}
];

@http:ServiceConfig {
    chunking: http:CHUNKING_ALWAYS
}
service / on new http:Listener(9090, httpVersion = http:HTTP_1_1) {

    resource function get albums() returns Album[] {
        return albums.toArray();
    }
}

Run the service as follows.

$ bal run http_service_chunking.bal

Invoke the service by executing the following cURL command in a new terminal.

$ curl -v localhost:9090/albums> GET /albums HTTP/1.1> Host: localhost:9090> User-Agent: curl/7.64.1> Accept: */*> < HTTP/1.1 200 OK< content-type: application/json< transfer-encoding: chunked< server: ballerina< date: Wed, 4 Jan 2023 21:14:48 +0530< [{"title":"Blue Train", "artist":"John Coltrane"}, {"title":"Jeru", "artist":"Gerry Mulligan"}]

Related links

PreviousCookies
NextSending headers