blob: 706a4354f5ff2c4f0616860e36dae7abd534cbf9 (
plain)
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
|
//! Thin HTTP GET helper over std.http.Client.
const std = @import("std");
const assert = std.debug.assert;
/// Largest response body we accept (the docs page is ~1 MB; allow generous slack).
pub const max_body = 32 * 1024 * 1024;
pub const Error = error{ HttpStatus, BodyTooLarge } || std.mem.Allocator.Error;
/// GET `url` and return the response body. Caller owns the returned slice.
/// Returns an error on any non-200 status so callers can skip that version.
pub fn get(allocator: std.mem.Allocator, client: *std.http.Client, url: []const u8) ![]u8 {
assert(url.len > 0);
var body: std.Io.Writer.Allocating = .init(allocator);
defer body.deinit();
const result = try client.fetch(.{
.location = .{ .url = url },
.response_writer = &body.writer,
});
if (result.status != .ok) return Error.HttpStatus;
if (body.writer.end > max_body) return Error.BodyTooLarge;
const out = try body.toOwnedSlice();
assert(out.len > 0);
return out;
}
|