Skip to content

Instantly share code, notes, and snippets.

@heyajulia
Created December 21, 2020 00:58
Show Gist options
  • Save heyajulia/0b445a5e18872efb470bbd47ccd5f841 to your computer and use it in GitHub Desktop.
Save heyajulia/0b445a5e18872efb470bbd47ccd5f841 to your computer and use it in GitHub Desktop.
[WIP] Making a HTTP request using cURL in Zig.
const c = @cImport({
@cInclude("curl/curl.h");
@cInclude("stdlib.h");
@cInclude("stddef.h");
});
const std = @import("std");
// XXX Trying to use c.size_t from stddef.h results in
// "container … has no member called 'size_t'".
//
// I *think* this is right.
const size_t = if (@typeInfo(usize).Int.bits == 64) u64 else u32;
fn ok(code: c.CURLcode) void {
if (code != @intToEnum(c.CURLcode, c.CURLE_OK)) {
// TODO: It would be better if this said something like: "cURL error: <error text>".
@panic(std.mem.span(c.curl_easy_strerror(code)));
}
}
fn write_data(buffer: *c_void, size: size_t, nmemb: size_t, userp: *c_void) callconv(.C) size_t {
// Size is always 1.
// TODO: get the data from buffer
// TODO: are we responsible for freeing buffer?
return ziggy_write_data(buffer, nmemb, userp);
}
/// A more "ziggy" version of write_data.
fn ziggy_write_data(buffer: *c_void, nmemb: size_t, userp: *c_void) size_t {
std.debug.print("nmemb: {}\n", .{nmemb});
return nmemb;
}
pub fn main() void {
ok(c.curl_global_init(c.CURL_GLOBAL_ALL));
defer c.curl_global_cleanup();
const handle = c.curl_easy_init();
defer c.curl_easy_cleanup(handle);
ok(c.curl_easy_setopt(handle, @intToEnum(c.CURLoption, c.CURLOPT_URL), "htps://www.apple.com"));
ok(c.curl_easy_setopt(handle, @intToEnum(c.CURLoption, c.CURLOPT_WRITEFUNCTION), write_data));
ok(c.curl_easy_perform(handle));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment