|
| 1 | +const std = @import("std"); |
| 2 | +const cli = @import("cli.zig"); |
| 3 | + |
| 4 | +pub const ExecuteError = error{ |
| 5 | + InvalidMethod, |
| 6 | + InvalidTarget, |
| 7 | +}; |
| 8 | + |
| 9 | +pub const Result = struct { |
| 10 | + status: std.http.Status, |
| 11 | + body: []u8, |
| 12 | + |
| 13 | + pub fn deinit(self: *Result, allocator: std.mem.Allocator) void { |
| 14 | + allocator.free(self.body); |
| 15 | + self.* = undefined; |
| 16 | + } |
| 17 | +}; |
| 18 | + |
| 19 | +pub fn run(allocator: std.mem.Allocator, opts: cli.ApiOptions) !void { |
| 20 | + var result = try execute(allocator, opts); |
| 21 | + defer result.deinit(allocator); |
| 22 | + |
| 23 | + const formatted = if (opts.pretty) |
| 24 | + try prettyBody(allocator, result.body) |
| 25 | + else |
| 26 | + try allocator.dupe(u8, result.body); |
| 27 | + defer allocator.free(formatted); |
| 28 | + |
| 29 | + if (formatted.len > 0) { |
| 30 | + try writeAll(std.fs.File.stdout(), formatted); |
| 31 | + if (formatted[formatted.len - 1] != '\n') { |
| 32 | + try writeAll(std.fs.File.stdout(), "\n"); |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + const code = @intFromEnum(result.status); |
| 37 | + if (code < 200 or code >= 300) { |
| 38 | + var buf: [64]u8 = undefined; |
| 39 | + const line = try std.fmt.bufPrint(&buf, "HTTP {d}\n", .{code}); |
| 40 | + try writeAll(std.fs.File.stderr(), line); |
| 41 | + return error.RequestFailed; |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +pub fn execute(allocator: std.mem.Allocator, opts: cli.ApiOptions) !Result { |
| 46 | + const method = parseMethod(opts.method) orelse return ExecuteError.InvalidMethod; |
| 47 | + const target = try normalizeTargetAlloc(allocator, opts.target); |
| 48 | + defer allocator.free(target); |
| 49 | + |
| 50 | + const url = try std.fmt.allocPrint(allocator, "http://{s}:{d}{s}", .{ opts.host, opts.port, target }); |
| 51 | + defer allocator.free(url); |
| 52 | + |
| 53 | + const request_body = try loadBodyAlloc(allocator, opts); |
| 54 | + defer if (request_body.owned) allocator.free(request_body.bytes); |
| 55 | + |
| 56 | + var auth_header: ?[]u8 = null; |
| 57 | + defer if (auth_header) |value| allocator.free(value); |
| 58 | + |
| 59 | + var header_storage: [2]std.http.Header = undefined; |
| 60 | + var header_count: usize = 0; |
| 61 | + if (request_body.bytes.len > 0) { |
| 62 | + header_storage[header_count] = .{ .name = "Content-Type", .value = opts.content_type }; |
| 63 | + header_count += 1; |
| 64 | + } |
| 65 | + if (opts.token) |token| { |
| 66 | + auth_header = try std.fmt.allocPrint(allocator, "Bearer {s}", .{token}); |
| 67 | + header_storage[header_count] = .{ .name = "Authorization", .value = auth_header.? }; |
| 68 | + header_count += 1; |
| 69 | + } |
| 70 | + |
| 71 | + var client: std.http.Client = .{ .allocator = allocator }; |
| 72 | + defer client.deinit(); |
| 73 | + |
| 74 | + var response_body: std.io.Writer.Allocating = .init(allocator); |
| 75 | + defer response_body.deinit(); |
| 76 | + |
| 77 | + const result = try client.fetch(.{ |
| 78 | + .location = .{ .url = url }, |
| 79 | + .method = method, |
| 80 | + .payload = payloadForFetch(method, request_body.bytes), |
| 81 | + .response_writer = &response_body.writer, |
| 82 | + .extra_headers = header_storage[0..header_count], |
| 83 | + }); |
| 84 | + |
| 85 | + return .{ |
| 86 | + .status = result.status, |
| 87 | + .body = try response_body.toOwnedSlice(), |
| 88 | + }; |
| 89 | +} |
| 90 | + |
| 91 | +fn writeAll(file: std.fs.File, bytes: []const u8) !void { |
| 92 | + var buf: [4096]u8 = undefined; |
| 93 | + var writer = file.writer(&buf); |
| 94 | + try writer.interface.writeAll(bytes); |
| 95 | + try writer.interface.flush(); |
| 96 | +} |
| 97 | + |
| 98 | +fn parseMethod(raw: []const u8) ?std.http.Method { |
| 99 | + if (std.ascii.eqlIgnoreCase(raw, "GET")) return .GET; |
| 100 | + if (std.ascii.eqlIgnoreCase(raw, "POST")) return .POST; |
| 101 | + if (std.ascii.eqlIgnoreCase(raw, "PUT")) return .PUT; |
| 102 | + if (std.ascii.eqlIgnoreCase(raw, "DELETE")) return .DELETE; |
| 103 | + if (std.ascii.eqlIgnoreCase(raw, "PATCH")) return .PATCH; |
| 104 | + if (std.ascii.eqlIgnoreCase(raw, "HEAD")) return .HEAD; |
| 105 | + if (std.ascii.eqlIgnoreCase(raw, "OPTIONS")) return .OPTIONS; |
| 106 | + return null; |
| 107 | +} |
| 108 | + |
| 109 | +fn normalizeTargetAlloc(allocator: std.mem.Allocator, raw: []const u8) ![]u8 { |
| 110 | + if (raw.len == 0) return ExecuteError.InvalidTarget; |
| 111 | + if (std.mem.startsWith(u8, raw, "http://") or std.mem.startsWith(u8, raw, "https://")) { |
| 112 | + return ExecuteError.InvalidTarget; |
| 113 | + } |
| 114 | + if (raw[0] == '/') return allocator.dupe(u8, raw); |
| 115 | + if (std.mem.startsWith(u8, raw, "api/")) return std.fmt.allocPrint(allocator, "/{s}", .{raw}); |
| 116 | + if (std.mem.eql(u8, raw, "health")) return allocator.dupe(u8, "/health"); |
| 117 | + return std.fmt.allocPrint(allocator, "/api/{s}", .{raw}); |
| 118 | +} |
| 119 | + |
| 120 | +const LoadedBody = struct { |
| 121 | + bytes: []const u8, |
| 122 | + owned: bool = false, |
| 123 | +}; |
| 124 | + |
| 125 | +fn loadBodyAlloc(allocator: std.mem.Allocator, opts: cli.ApiOptions) !LoadedBody { |
| 126 | + if (opts.body_file) |path| { |
| 127 | + if (std.mem.eql(u8, path, "-")) { |
| 128 | + const bytes = try std.fs.File.stdin().readToEndAlloc(allocator, 8 * 1024 * 1024); |
| 129 | + return .{ .bytes = bytes, .owned = true }; |
| 130 | + } |
| 131 | + const file = try std.fs.cwd().openFile(path, .{}); |
| 132 | + defer file.close(); |
| 133 | + const bytes = try file.readToEndAlloc(allocator, 8 * 1024 * 1024); |
| 134 | + return .{ .bytes = bytes, .owned = true }; |
| 135 | + } |
| 136 | + if (opts.body) |body| return .{ .bytes = body, .owned = false }; |
| 137 | + return .{ .bytes = "", .owned = false }; |
| 138 | +} |
| 139 | + |
| 140 | +fn payloadForFetch(method: std.http.Method, body: []const u8) ?[]const u8 { |
| 141 | + if (body.len > 0) return body; |
| 142 | + if (method.requestHasBody()) return body; |
| 143 | + return null; |
| 144 | +} |
| 145 | + |
| 146 | +fn prettyBody(allocator: std.mem.Allocator, body: []const u8) ![]u8 { |
| 147 | + if (body.len == 0) return allocator.dupe(u8, body); |
| 148 | + |
| 149 | + const parsed = std.json.parseFromSlice(std.json.Value, allocator, body, .{ |
| 150 | + .allocate = .alloc_always, |
| 151 | + .ignore_unknown_fields = true, |
| 152 | + }) catch return allocator.dupe(u8, body); |
| 153 | + defer parsed.deinit(); |
| 154 | + |
| 155 | + return std.json.Stringify.valueAlloc(allocator, parsed.value, .{ |
| 156 | + .whitespace = .indent_2, |
| 157 | + }); |
| 158 | +} |
| 159 | + |
| 160 | +test "normalizeTargetAlloc keeps explicit API path" { |
| 161 | + const value = try normalizeTargetAlloc(std.testing.allocator, "/api/status"); |
| 162 | + defer std.testing.allocator.free(value); |
| 163 | + try std.testing.expectEqualStrings("/api/status", value); |
| 164 | +} |
| 165 | + |
| 166 | +test "normalizeTargetAlloc prefixes api namespace" { |
| 167 | + const value = try normalizeTargetAlloc(std.testing.allocator, "instances/nullclaw/demo"); |
| 168 | + defer std.testing.allocator.free(value); |
| 169 | + try std.testing.expectEqualStrings("/api/instances/nullclaw/demo", value); |
| 170 | +} |
| 171 | + |
| 172 | +test "normalizeTargetAlloc supports health shorthand" { |
| 173 | + const value = try normalizeTargetAlloc(std.testing.allocator, "health"); |
| 174 | + defer std.testing.allocator.free(value); |
| 175 | + try std.testing.expectEqualStrings("/health", value); |
| 176 | +} |
| 177 | + |
| 178 | +test "parseMethod accepts common verbs case-insensitively" { |
| 179 | + try std.testing.expectEqual(std.http.Method.DELETE, parseMethod("delete").?); |
| 180 | + try std.testing.expectEqual(std.http.Method.PATCH, parseMethod("PATCH").?); |
| 181 | + try std.testing.expect(parseMethod("TRACE") == null); |
| 182 | +} |
| 183 | + |
| 184 | +test "prettyBody indents JSON output" { |
| 185 | + const value = try prettyBody(std.testing.allocator, "{\"ok\":true}"); |
| 186 | + defer std.testing.allocator.free(value); |
| 187 | + try std.testing.expect(std.mem.indexOf(u8, value, "\n") != null); |
| 188 | + try std.testing.expect(std.mem.indexOf(u8, value, " \"ok\"") != null); |
| 189 | +} |
| 190 | + |
| 191 | +test "payloadForFetch keeps empty body for POST" { |
| 192 | + try std.testing.expect(payloadForFetch(.POST, "") != null); |
| 193 | + try std.testing.expect(payloadForFetch(.GET, "") == null); |
| 194 | +} |
0 commit comments