Repository navigation
Expand file tree
/
Copy pathhtmlStream.zig
More file actions
48 lines (39 loc) · 1.43 KB
/
Copy pathhtmlStream.zig
File metadata and controls
48 lines (39 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
//! Example: Streaming HTML Parsing via std.Io.Reader
//!
//! Demonstrates:
//! 1. Streaming HTML parsing from a chunked or streaming reader without loading unbounded data
//! 2. Bounded memory limits
//! 3. Extracting elements on the resulting document
//!
//! Run with: `zig build run-html-stream`
const std = @import("std");
const httpx = @import("httpx");
pub fn main() !void {
var gpa: std.heap.DebugAllocator(.{}) = .init;
defer _ = gpa.deinit();
const allocator = gpa.allocator();
std.debug.print("==> HTTPX Streaming HTML Parser Demo\n\n", .{});
const chunkedHtml =
\\<!DOCTYPE html>
\\<html>
\\<head><title>Streaming Page</title></head>
\\<body>
\\ <div class="stream-content">
\\ <p>This document was streamed chunk by chunk via std.Io.Reader.</p>
\\ </div>
\\</body>
\\</html>
;
var reader = std.Io.Reader.fixed(chunkedHtml);
var p = httpx.parsing.Parser.init(allocator, .{});
// Parse stream with a 1 MB limit
var doc = try p.parseStream(&reader, 1024 * 1024);
defer doc.deinit();
const title = try doc.title();
std.debug.print("Document Title: '{s}'\n", .{title});
if (try doc.selectFirst(".stream-content p")) |pNode| {
const text = try pNode.text();
std.debug.print("Stream Content Paragraph: '{s}'\n", .{text});
}
std.debug.print("\nStreaming HTML verification successful.\n", .{});
}