Skip to content

Instantly share code, notes, and snippets.

@peterhellberg
Last active September 16, 2024 08:02
Show Gist options
  • Select an option

  • Save peterhellberg/de7b7ca454d4722fdc8b46f9b4c052f4 to your computer and use it in GitHub Desktop.

Select an option

Save peterhellberg/de7b7ca454d4722fdc8b46f9b4c052f4 to your computer and use it in GitHub Desktop.
HTTP GET request using Zig ⚡ 0.14.0-dev.1210+54e48f7b7
const std = @import("std");
pub fn build(b: *std.Build) void {
const exe = b.addExecutable(.{
.name = "whatthecommit",
.root_source_file = b.path("whatthecommit.zig"),
.target = b.standardTargetOptions(.{}),
.optimize = b.standardOptimizeOption(.{}),
});
b.installArtifact(exe);
const run_cmd = b.addRunArtifact(exe);
run_cmd.step.dependOn(b.getInstallStep());
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
}
const std = @import("std");
const http = std.http;
const print = std.debug.print;
// URL for fetching a random message.
const RANDOM_MESSAGE_URL = "https://whatthecommit.com/index.txt";
/// Returns a random message.
fn getRandomMessage(allocator: std.mem.Allocator) ![]u8 {
// Parse the URI.
const uri = try std.Uri.parse(RANDOM_MESSAGE_URL);
// Create an HTTP client.
var client = http.Client{ .allocator = allocator };
// Release all associated resources with the client.
defer client.deinit();
const server_header_buffer: []u8 = try allocator.alloc(u8, 1024 * 8);
defer allocator.free(server_header_buffer);
// Make the connection to the server.
var req = try client.open(.GET, uri, .{
.server_header_buffer = server_header_buffer,
});
defer req.deinit();
try req.send();
try req.finish();
try req.wait();
print("Response status: {d}\n\n", .{req.response.status});
// Print out the headers
print("{s}\n", .{req.response.iterateHeaders().bytes});
// Read the entire response body, but only allow it to allocate 1024 * 8 of memory.
return req.reader().readAllAlloc(allocator, 1024 * 8);
}
/// Entry-point of the application.
pub fn main() !void {
// Create an allocator.
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
// Get a random message.
const message = try getRandomMessage(allocator);
defer allocator.free(message);
const out = std.io.getStdOut().writer();
// Print out the message.
try out.print("{s}\n", .{message});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment