Sample code for 30+ languages & platforms
Zig

HTTP Download to Stream

See more REST Examples

Demonstrates how to stream the response body directly to a stream, which in this case is to a file stream.

Chilkat Zig Downloads

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

    // This example requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    const rest = try chilkat.Rest.init();
    defer rest.deinit();

    // The URL we want to download is:
    // https://github.com/chilkatsoft/OAuth2-CSharp-Desktop/archive/master.zip
    const url = try chilkat.Url.init();
    defer url.deinit();
    url.parseUrl("https://github.com/chilkatsoft/OAuth2-CSharp-Desktop/archive/master.zip") catch {};

    // Connect to the web server
    const b_auto_reconnect = true;
    rest.connect(try url.getHost(alloc), url.getPort(), url.getSsl(), b_auto_reconnect) catch {
        std.debug.print("{s}\n", .{try rest.getLastErrorText(alloc)});
        return;
    };

    rest.sendReqNoBody("GET", try url.getPath(alloc)) catch {
        std.debug.print("{s}\n", .{try rest.getLastErrorText(alloc)});
        return;
    };

    // Read the response header.
    const response_status_code = rest.readResponseHeader();
    if (response_status_code < 0) {
        std.debug.print("{s}\n", .{try rest.getLastErrorText(alloc)});
        return;
    }

    std.debug.print("Response status code = {d}\n", .{response_status_code});

    // We expect a 200 response status if the file data is coming.
    // Otherwise, we'll get a string response body with an error message(or no response body).
    if (response_status_code == 200) {
        const body_stream = try chilkat.Stream.init();
        defer body_stream.deinit();

        // The stream's sink will be a file.
        body_stream.setSinkFile("qa_output/OAuth2-CSharp-Desktop/archive/master.zip");

        // Read the response body to the stream.  Given that we've
        // set the stream's sink to a file, it will stream directly
        // to the file.
        rest.readRespBodyStream(body_stream, true) catch {
            std.debug.print("{s}\n", .{try rest.getLastErrorText(alloc)});
            return;
        };

        std.debug.print("Successfully downloaded the file.\n", .{});
    } else {
        const err_response = rest.readRespBodyString(alloc) catch "";
        if (!rest.getLastMethodSuccess()) {
            std.debug.print("{s}\n", .{try rest.getLastErrorText(alloc)});
        } else {
            std.debug.print("{s}\n", .{err_response});
        }
    }
}