From 486628f42e5f9b4ab75f35995bce7b46e49995de Mon Sep 17 00:00:00 2001 From: Ekaitz Zarraga Date: Fri, 1 Dec 2023 20:31:30 +0100 Subject: parameterize location --- src/main.zig | 4 +++- src/weatherFetcher.zig | 25 ++++++++++++++++--------- 2 files changed, 19 insertions(+), 10 deletions(-) diff --git a/src/main.zig b/src/main.zig index ba479e9..81317f1 100644 --- a/src/main.zig +++ b/src/main.zig @@ -9,7 +9,9 @@ pub fn main() !void{ const args = try std.process.argsAlloc(allocator); defer std.process.argsFree(allocator, args); - var daily = try weatherFetcher.getDailyData(allocator); + var daily = try weatherFetcher.getDailyData(allocator, weatherFetcher.Location{ + .lat=52.52, .lon=13.41, + }); defer daily.deinit(); const stdout = std.io.getStdOut().writer(); diff --git a/src/weatherFetcher.zig b/src/weatherFetcher.zig index be99d5c..42847f9 100644 --- a/src/weatherFetcher.zig +++ b/src/weatherFetcher.zig @@ -6,6 +6,10 @@ const expect = std.testing.expect; const http = @import("./http.zig"); +pub const Location = struct { + lat: f64, + lon: f64, +}; pub const DailyDataSchema = struct { latitude: f64, @@ -48,19 +52,22 @@ pub const DailyData = struct{ /// Gets Daily Data. Allocates and returns an DailyData struct that must be /// .deinit() later -pub fn getDailyData(allocator: std.mem.Allocator) !DailyData { +pub fn getDailyData(allocator: std.mem.Allocator, location: Location) !DailyData { const stream = try net.tcpConnectToHost(allocator, "api.open-meteo.com", 80); defer stream.close(); const writer = stream.writer(); - try writer.writeAll( "GET /v1/forecast" ++ - "?latitude=52.52" ++ - "&longitude=13.41" ++ - "&hourly=temperature_2m" ++ " HTTP/1.1\r\n" ++ - "Host: api.open-meteo.com\r\n" ++ - "Connection: keep-alive\r\n" ++ - "Accept-Encoding: identity\r\n" ++ - "\r\n"); + const request = try std.fmt.allocPrint(allocator, + "GET /v1/forecast" ++ + "?latitude={d}" ++ + "&longitude={d}" ++ + "&hourly=temperature_2m" ++ " HTTP/1.1\r\n" ++ + "Host: api.open-meteo.com\r\n" ++ + "Connection: keep-alive\r\n" ++ + "Accept-Encoding: identity\r\n" ++ "\r\n", .{location.lat, location.lon}); + defer allocator.free(request); + + try writer.writeAll(request); const reader = stream.reader(); var response = try http.HttpResponseParser.init(allocator); -- cgit v1.2.3