From c8be63e589003e920d41586a39078ae2790f7440 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81d=C3=A1m=20Kov=C3=A1cs?= Date: Thu, 22 May 2025 14:57:53 +0200 Subject: [PATCH] feat: httpClient header --- src/httpClient.zig | 36 ++++++++++++++++++++++++++++++++++-- src/main.zig | 13 ++++++++++--- 2 files changed, 44 insertions(+), 5 deletions(-) diff --git a/src/httpClient.zig b/src/httpClient.zig index 5e2e294..9cf5d1a 100644 --- a/src/httpClient.zig +++ b/src/httpClient.zig @@ -67,9 +67,41 @@ fn send_http_request(pcb: ?*cNet.tcp_pcb, context: *HttpContext) !void { .percent_encoded => |v| v, }; - const request_data = .{ @tagName(context.request.method), path_string, host_string, context.request.body.len, context.request.body }; + var header_content = try std.fmt.allocPrint(context.client.allocator, "", .{}); + defer context.client.allocator.free(header_content); - const raw_request = try std.fmt.allocPrint(context.client.allocator, "{s} {s} HTTP/1.1\r\nHost: {s}\r\nTitle: Csengo\r\nPriority: 5\r\nX-Tags: bell\r\nContent-Length: {}\r\n\r\n{s}", request_data); + for (context.request.headers) |header| { + const old_header_content = header_content; + header_content = try std.fmt.allocPrint(context.client.allocator, "{s}{s}: {s}\r\n", .{ header_content, header.name, header.value }); + context.client.allocator.free(old_header_content); + } + const final_header_content = std.mem.trimRight(u8, header_content, "\r\n"); + + const request_data = .{ + .method = @tagName(context.request.method), + .path = path_string, + .host = host_string, + .headers = final_header_content, + .content_length = context.request.body.len, + .content = context.request.body, + }; + + // \\Title: Csengo\r + // \\Priority: 5\r + // \\X-Tags: bell\r + const template = + \\{[method]s} {[path]s} HTTP/1.1\r + \\Host: {[host]s}\r + \\{[headers]s}\r + \\Content-Length: {[content_length]}\r + \\\r + \\{[content]s} + ; + const raw_request = try std.fmt.allocPrint( + context.client.allocator, + template, + request_data, + ); print("Sending request"); print(raw_request); diff --git a/src/main.zig b/src/main.zig index d947caf..c883df5 100644 --- a/src/main.zig +++ b/src/main.zig @@ -90,9 +90,16 @@ pub fn send_doorbell_notification() !void { var client = &httpClient.Client{ .allocator = allocator }; - const request = &httpClient.HttpRequest{ .method = .POST, .url = try std.Uri.parse(appSettings.ntfy_url), .body = "Csengo", .headers = &[_]httpClient.HttpHeader{ - httpClient.HttpHeader{ .name = "Title", .value = "Csengo" }, - } }; + const request = &httpClient.HttpRequest{ + .method = .POST, + .url = try std.Uri.parse(appSettings.ntfy_url), + .body = "Csengo", + .headers = &[_]httpClient.HttpHeader{ + .{ .name = "Title", .value = "Csengo" }, + .{ .name = "Priority", .value = "5" }, + .{ .name = "X-Tags", .value = "bell" }, + }, + }; const response = try client.sendRequest(request); if (response) |r| { defer allocator.destroy(r);