Skip to content

Commit 06ac766

Browse files
committed
start on the client piece, wire up a main example
1 parent 875f65e commit 06ac766

8 files changed

Lines changed: 390 additions & 84 deletions

File tree

‎.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
11
.zig-cache/
2+
zig-out/

‎build.zig‎

Lines changed: 9 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,63 +1,39 @@
11
const std = @import("std");
22

3-
// Although this function looks imperative, note that its job is to
4-
// declaratively construct a build graph that will be executed by an external
5-
// runner.
63
pub fn build(b: *std.Build) void {
7-
// Standard target options allows the person running `zig build` to choose
8-
// what target to build for. Here we do not override the defaults, which
9-
// means any target is allowed, and the default is native. Other options
10-
// for restricting supported target set are available.
11-
const target = b.standardTargetOptions(.{});
4+
const dependencies = [_][]const u8{
5+
"clap",
6+
};
127

13-
// Standard optimization options allow the person running `zig build` to select
14-
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. Here we do not
15-
// set a preferred release mode, allowing the user to decide how to optimize.
8+
const target = b.standardTargetOptions(.{});
169
const optimize = b.standardOptimizeOption(.{});
1710

18-
// We will also create a module for our other entry point, 'main.zig'.
1911
const exe_mod = b.createModule(.{
20-
// `root_source_file` is the Zig "entry point" of the module. If a module
21-
// only contains e.g. external object files, you can make this `null`.
22-
// In this case the main source file is merely a path, however, in more
23-
// complicated build scripts, this could be a generated file.
2412
.root_source_file = b.path("src/main.zig"),
2513
.target = target,
2614
.optimize = optimize,
2715
});
2816

29-
// This creates another `std.Build.Step.Compile`, but this one builds an executable
30-
// rather than a static library.
3117
const exe = b.addExecutable(.{
3218
.name = "httpspec",
3319
.root_module = exe_mod,
3420
});
3521

36-
// This declares intent for the executable to be installed into the
37-
// standard location when the user invokes the "install" step (the default
38-
// step when running `zig build`).
22+
for (dependencies) |dependency| {
23+
const dep = b.dependency(dependency, .{});
24+
exe.root_module.addImport(dependency, dep.module(dependency));
25+
}
26+
3927
b.installArtifact(exe);
4028

41-
// This *creates* a Run step in the build graph, to be executed when another
42-
// step is evaluated that depends on it. The next line below will establish
43-
// such a dependency.
4429
const run_cmd = b.addRunArtifact(exe);
4530

46-
// By making the run step depend on the install step, it will be run from the
47-
// installation directory rather than directly from within the cache directory.
48-
// This is not necessary, however, if the application depends on other installed
49-
// files, this ensures they will be present and in the expected location.
5031
run_cmd.step.dependOn(b.getInstallStep());
5132

52-
// This allows the user to pass arguments to the application in the build
53-
// command itself, like this: `zig build run -- arg1 arg2 etc`
5433
if (b.args) |args| {
5534
run_cmd.addArgs(args);
5635
}
5736

58-
// This creates a build step. It will be visible in the `zig build --help` menu,
59-
// and can be selected like this: `zig build run`
60-
// This will evaluate the `run` step rather than the default, which is "install".
6137
const run_step = b.step("run", "Run the app");
6238
run_step.dependOn(&run_cmd.step);
6339

@@ -67,9 +43,6 @@ pub fn build(b: *std.Build) void {
6743

6844
const run_exe_unit_tests = b.addRunArtifact(exe_unit_tests);
6945

70-
// Similar to creating the run step earlier, this exposes a `test` step to
71-
// the `zig build --help` menu, providing a way for the user to request
72-
// running the unit tests.
7346
const test_step = b.step("test", "Run unit tests");
7447
test_step.dependOn(&run_exe_unit_tests.step);
7548
}

‎build.zig.zon‎

Lines changed: 4 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -36,45 +36,11 @@
3636
// Once all dependencies are fetched, `zig build` no longer requires
3737
// internet connectivity.
3838
.dependencies = .{
39-
// See `zig fetch --save <url>` for a command-line interface for adding dependencies.
40-
//.example = .{
41-
// // When updating this field to a new URL, be sure to delete the corresponding
42-
// // `hash`, otherwise you are communicating that you expect to find the old hash at
43-
// // the new URL. If the contents of a URL change this will result in a hash mismatch
44-
// // which will prevent zig from using it.
45-
// .url = "https://example.com/foo.tar.gz",
46-
//
47-
// // This is computed from the file contents of the directory of files that is
48-
// // obtained after fetching `url` and applying the inclusion rules given by
49-
// // `paths`.
50-
// //
51-
// // This field is the source of truth; packages do not come from a `url`; they
52-
// // come from a `hash`. `url` is just one of many possible mirrors for how to
53-
// // obtain a package matching this `hash`.
54-
// //
55-
// // Uses the [multihash](https://multiformats.io/multihash/) format.
56-
// .hash = "...",
57-
//
58-
// // When this is provided, the package is found in a directory relative to the
59-
// // build root. In this case the package's hash is irrelevant and therefore not
60-
// // computed. This field and `url` are mutually exclusive.
61-
// .path = "foo",
62-
//
63-
// // When this is set to `true`, a package is declared to be lazily
64-
// // fetched. This makes the dependency only get fetched if it is
65-
// // actually used.
66-
// .lazy = false,
67-
//},
39+
.clap = .{
40+
.url = "git+https://github.com/Hejsil/zig-clap#cc5c6a5d71a317ed4b0ad776842d1d0655f72d0a",
41+
.hash = "clap-0.10.0-oBajB7jkAQAZ4cKLlzkeV9mDu2yGZvtN2QuOyfAfjBij",
42+
},
6843
},
69-
70-
// Specifies the set of files and directories that are included in this package.
71-
// Only files and directories listed here are included in the `hash` that
72-
// is computed for this package. Only files listed here will remain on disk
73-
// when using the zig package manager. As a rule of thumb, one should list
74-
// files required for compilation plus any license(s).
75-
// Paths are relative to the build root. Use the empty string (`""`) to refer to
76-
// the build root itself.
77-
// A directory listed here means that all files within, recursively, are included.
7844
.paths = .{
7945
"build.zig",
8046
"build.zig.zon",

‎src/client/http_client.zig‎

Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
1+
const std = @import("std");
2+
const http = std.http;
3+
const ArrayList = std.ArrayList;
4+
const Allocator = std.mem.Allocator;
5+
const Uri = std.Uri;
6+
const httpfiles = @import("./parser");
7+
8+
pub const HttpResponse = struct {
9+
status_code: u16,
10+
headers: ArrayList(http.Header),
11+
body: []u8,
12+
allocator: Allocator,
13+
14+
pub fn init(allocator: Allocator) HttpResponse {
15+
return .{
16+
.status_code = 0,
17+
.headers = ArrayList(http.Header).init(allocator),
18+
.body = &[_]u8{},
19+
.allocator = allocator,
20+
};
21+
}
22+
23+
pub fn deinit(self: *HttpResponse) void {
24+
for (self.headers.items) |header| {
25+
self.allocator.free(header.name);
26+
self.allocator.free(header.value);
27+
}
28+
self.headers.deinit();
29+
if (self.body.len > 0) {
30+
self.allocator.free(self.body);
31+
}
32+
}
33+
};
34+
35+
pub const HttpClient = struct {
36+
allocator: Allocator,
37+
client: http.Client,
38+
39+
pub fn init(allocator: Allocator) HttpClient {
40+
return .{
41+
.allocator = allocator,
42+
.client = http.Client{ .allocator = allocator },
43+
};
44+
}
45+
46+
pub fn deinit(self: *HttpClient) void {
47+
self.client.deinit();
48+
}
49+
50+
pub fn execute(self: *HttpClient, request: *const httpfiles.HttpRequest) !HttpResponse {
51+
if (request.method == null) {
52+
return error.MissingHttpMethod;
53+
}
54+
55+
// Parse the URL
56+
const uri = try Uri.parse(request.url);
57+
58+
// Create the HTTP request
59+
var req = try self.client.open(request.method.?.toStdMethod(), uri, .{
60+
.server_header_buffer = try self.allocator.alloc(u8, 8192),
61+
});
62+
defer req.deinit();
63+
64+
// Add headers
65+
for (request.headers.items) |header| {
66+
try req.headers.append(header.name, header.value);
67+
}
68+
69+
// Set content length if we have a body
70+
if (request.body) |body| {
71+
req.transfer_encoding = .{ .content_length = body.len };
72+
} else {
73+
req.transfer_encoding = .{ .content_length = 0 };
74+
}
75+
76+
// Send the request
77+
try req.send();
78+
79+
// Send body if present
80+
if (request.body) |body| {
81+
try req.writeAll(body);
82+
}
83+
84+
try req.finish();
85+
86+
// Wait for response
87+
try req.wait();
88+
89+
// Read the response
90+
var response = HttpResponse.init(self.allocator);
91+
response.status_code = req.response.status.code();
92+
93+
// Copy response headers
94+
var header_iterator = req.response.iterateHeaders();
95+
while (header_iterator.next()) |header| {
96+
const name = try self.allocator.dupe(u8, header.name);
97+
const value = try self.allocator.dupe(u8, header.value);
98+
try response.headers.append(.{ .name = name, .value = value });
99+
}
100+
101+
// Read response body
102+
const body_reader = req.reader();
103+
const body_content = try body_reader.readAllAlloc(self.allocator, std.math.maxInt(usize));
104+
response.body = body_content;
105+
106+
return response;
107+
}
108+
109+
pub fn executeRequests(self: *HttpClient, requests: []const httpfiles.HttpRequest) !ArrayList(HttpResponse) {
110+
var responses = ArrayList(HttpResponse).init(self.allocator);
111+
errdefer {
112+
for (responses.items) |*response| {
113+
response.deinit();
114+
}
115+
responses.deinit();
116+
}
117+
118+
for (requests) |*request| {
119+
const response = try self.execute(request);
120+
try responses.append(response);
121+
}
122+
123+
return responses;
124+
}
125+
};
126+
127+
// Utility function to print response details
128+
pub fn printResponse(response: *const HttpResponse) void {
129+
std.debug.print("Status: {d}\n", .{response.status_code});
130+
std.debug.print("Headers:\n");
131+
for (response.headers.items) |header| {
132+
std.debug.print(" {s}: {s}\n", .{ header.name, header.value });
133+
}
134+
std.debug.print("Body ({d} bytes):\n{s}\n", .{ response.body.len, response.body });
135+
std.debug.print("---\n");
136+
}
137+
138+
test "HttpClient basic functionality" {
139+
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
140+
defer _ = gpa.deinit();
141+
const allocator = gpa.allocator();
142+
143+
var client = HttpClient.init(allocator);
144+
defer client.deinit();
145+
146+
// Create a simple GET request
147+
var request = httpfiles.HttpRequest.init(allocator);
148+
defer request.deinit(allocator);
149+
150+
request.method = .GET;
151+
request.url = "https://httpbin.org/status/200";
152+
153+
// Execute the request
154+
var response = try client.execute(&request);
155+
defer response.deinit();
156+
157+
// Check that we got a 200 status
158+
try std.testing.expectEqual(@as(u16, 200), response.status_code);
159+
}

0 commit comments

Comments
 (0)