-
Notifications
You must be signed in to change notification settings - Fork 3
/
c-libcurl.zig
50 lines (40 loc) · 1.9 KB
/
c-libcurl.zig
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// look at the `curl` target in Makefile
const std = @import("std");
const cURL = @cImport({
@cInclude("curl/curl.h");
});
pub fn main() !void {
var arena_state = std.heap.ArenaAllocator.init(std.heap.c_allocator);
defer arena_state.deinit();
var allocator = &arena_state.allocator;
// global curl init, or fail
if (cURL.curl_global_init(cURL.CURL_GLOBAL_ALL) != cURL.CURLE_OK)
return error.CURLGlobalInitFailed;
defer cURL.curl_global_cleanup();
// curl easy handle init, or fail
const handle = cURL.curl_easy_init() orelse return error.CURLHandleInitFailed;
defer cURL.curl_easy_cleanup(handle);
var response_buffer = std.ArrayList(u8).init(allocator);
// superfluous when using an arena allocator, but
// important if the allocator implementation changes
defer response_buffer.deinit();
// setup curl options
if (cURL.curl_easy_setopt(handle, cURL.CURLOPT_URL, "https://ziglang.org") != cURL.CURLE_OK)
return error.CouldNotSetURL;
// set write function callbacks
if (cURL.curl_easy_setopt(handle, cURL.CURLOPT_WRITEFUNCTION, writeToArrayListCallback) != cURL.CURLE_OK)
return error.CouldNotSetWriteCallback;
if (cURL.curl_easy_setopt(handle, cURL.CURLOPT_WRITEDATA, &response_buffer) != cURL.CURLE_OK)
return error.CouldNotSetWriteCallback;
// perform
if (cURL.curl_easy_perform(handle) != cURL.CURLE_OK)
return error.FailedToPerformRequest;
std.log.info("Got response of {d} bytes", .{response_buffer.items.len});
std.debug.print("{s}\n", .{response_buffer.items});
}
fn writeToArrayListCallback(data: *c_void, size: c_uint, nmemb: c_uint, user_data: *c_void) callconv(.C) c_uint {
var buffer = @intToPtr(*std.ArrayList(u8), @ptrToInt(user_data));
var typed_data = @intToPtr([*]u8, @ptrToInt(data));
buffer.appendSlice(typed_data[0 .. nmemb * size]) catch return 0;
return nmemb * size;
}