From 796fca3d255da3c835a9133d180d341c661e6cdb Mon Sep 17 00:00:00 2001 From: Meghan Denny Date: Thu, 29 Apr 2021 22:33:29 -0700 Subject: [PATCH] add example program --- build.zig | 23 +++++++++++++++++++++++ src/main.zig | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 build.zig create mode 100644 src/main.zig diff --git a/build.zig b/build.zig new file mode 100644 index 0000000000000000000000000000000000000000..83de6d152ea7d0d17b33320c2ed62d4b3768a70c --- /dev/null +++ b/build.zig @@ -0,0 +1,23 @@ +const std = @import("std"); +const deps = @import("./deps.zig"); + +pub fn build(b: *std.build.Builder) void { + const target = b.standardTargetOptions(.{}); + + const mode = b.standardReleaseOptions(); + + const exe = b.addExecutable("zig-json", "src/main.zig"); + exe.setTarget(target); + exe.setBuildMode(mode); + deps.addAllTo(exe); + exe.install(); + + const run_cmd = exe.run(); + run_cmd.step.dependOn(b.getInstallStep()); + if (b.args) |args| { + run_cmd.addArgs(args); + } + + const run_step = b.step("run", "Run the app"); + run_step.dependOn(&run_cmd.step); +} diff --git a/src/main.zig b/src/main.zig new file mode 100644 index 0000000000000000000000000000000000000000..c46ab2f5814055365a90412fcb8a5f2da4a0a24f --- /dev/null +++ b/src/main.zig @@ -0,0 +1,33 @@ +const std = @import("std"); + +const json = @import("json"); +const zfetch = @import("zfetch"); + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + const alloc = &gpa.allocator; + + const url = "https://old.reddit.com/r/Zig/.json"; + + const req = try zfetch.Request.init(alloc, url, null); + defer req.deinit(); + + try req.do(.GET, null, null); + const r = req.reader(); + + const body_content = try r.readAllAlloc(alloc, std.math.maxInt(usize)); + const val = try json.parse(alloc, body_content); + + std.log.info("hot posts from r/Zig", .{}); + std.log.info("", .{}); + + var count: usize = 1; + for (val.fetch(.{ "data", "children" }).?.Array) |ch| { + const post = ch.get("data").?; + const title = post.get("title").?.String; + const author = post.get("author").?.String; + std.log.info("{}: {s} -- u/{s} ", .{ count, title, author }); + count += 1; + } + _ = std.math.lossyCast(i32, 2.4); +} -- 2.54.0