Zig
Zig
(using AWS Signature Version 2) Streaming Download to File
See more Amazon S3 (new) Examples
The main purpose of this example is to demonstrate how to use the older Signature Version 2 authentication w/ S3. It uses V2 authentication to download a file.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;
// The file is located in the bucket named "chilkat100", which becomes part of the domain:
try rest.connect("chilkat100.s3.amazonaws.com", port, b_tls, b_auto_reconnect);
// 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");
// For AWS Signature Version 2, the following two properties need to be set:
auth_aws.setSignatureVersion(2);
// See http://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html#ConstructingTheCanonicalizedResourceElement
auth_aws.setCanonicalizedResourceV2("/chilkat100/starfish.jpg");
try rest.setAuthAws(auth_aws);
// 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});
}
}
}