Zig
Zig
REST Stream Response to File (Streaming Download) (Amazon S3)
See more Amazon S3 (new) Examples
Demonstrates how to stream the response body directly to a file. (The example shows how to stream a JPG from the Amazon S3 service.)Chilkat Zig Downloads
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();
// Connect to the Amazon AWS REST server.
const b_tls = true;
const port = 443;
const b_auto_reconnect = true;
try rest.connect("s3.amazonaws.com", port, b_tls, b_auto_reconnect);
// ----------------------------------------------------------------------------
// Important: For buckets created in regions outside us-east-1,
// there are three important changes that need to be made.
// See Working with S3 Buckets in Non-us-east-1 Regions for the details.
// ----------------------------------------------------------------------------
// Provide AWS credentials for the REST call.
const auth_aws = try chilkat.AuthAws.init();
defer auth_aws.deinit();
auth_aws.setAccessKey("AWS_ACCESS_KEY");
auth_aws.setSecretKey("AWS_SECRET_KEY");
auth_aws.setServiceName("s3");
try rest.setAuthAws(auth_aws);
// Set the bucket name via the HOST header.
// In this case, the bucket name is "chilkat100".
rest.setHost("chilkat100.s3.amazonaws.com");
// Send the request to download the JPG.
rest.sendReqNoBody("GET", "/starfish.jpg") 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 JPG 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/starfish.jpg");
// 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 received the JPG 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});
}
}
}