forked from jiacai2050/zig-curl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
basic.zig
84 lines (72 loc) · 2.25 KB
/
basic.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
const std = @import("std");
const println = @import("util.zig").println;
const mem = std.mem;
const Allocator = mem.Allocator;
const curl = @import("curl");
const Easy = curl.Easy;
fn get(allocator: Allocator, easy: Easy) !void {
const resp = try easy.get("https://httpbin.org/anything");
defer resp.deinit();
const body = resp.body.?.items;
std.debug.print("Status code: {d}\nBody: {s}\n", .{
resp.status_code,
body,
});
const Response = struct {
headers: struct {
Host: []const u8,
},
method: []const u8,
};
const parsed = try std.json.parseFromSlice(Response, allocator, body, .{
.ignore_unknown_fields = true,
});
defer parsed.deinit();
try std.testing.expectEqualDeep(parsed.value, Response{
.headers = .{ .Host = "httpbin.org" },
.method = "GET",
});
}
fn post(allocator: Allocator, easy: Easy) !void {
const payload =
\\{"name": "John", "age": 15}
;
const resp = try easy.post("https://httpbin.org/anything", "application/json", payload);
defer resp.deinit();
std.debug.print("Status code: {d}\nBody: {s}\n", .{
resp.status_code,
resp.body.?.items,
});
const Response = struct {
headers: struct {
@"Content-Type": []const u8,
},
json: struct {
name: []const u8,
age: u32,
},
method: []const u8,
};
const parsed = try std.json.parseFromSlice(Response, allocator, resp.body.?.items, .{ .ignore_unknown_fields = true });
defer parsed.deinit();
try std.testing.expectEqualDeep(parsed.value, Response{
.headers = .{ .@"Content-Type" = "application/json" },
.json = .{ .name = "John", .age = 15 },
.method = "POST",
});
}
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer if (gpa.deinit() != .ok) @panic("leak");
const allocator = gpa.allocator();
const ca_bundle = try curl.allocCABundle(allocator);
defer ca_bundle.deinit();
const easy = try Easy.init(allocator, .{
.ca_bundle = ca_bundle,
});
defer easy.deinit();
println("GET demo");
try get(allocator, easy);
println("POST demo");
try post(allocator, easy);
}