Repository navigation
Expand file tree
/
Copy pathliveReload.zig
More file actions
84 lines (70 loc) · 2.48 KB
/
Copy pathliveReload.zig
File metadata and controls
84 lines (70 loc) · 2.48 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
//! Example: Live Reload Server with SSE & Hot CSS Reloading
//!
//! Demonstrates:
//! 1. Server serving dynamic HTML and CSS
//! 2. Live reload script injection
//! 3. Background file watcher triggering reload events
//!
//! Run with: `zig build run-live-reload`
const std = @import("std");
const httpx = @import("httpx");
fn indexHandler(ctx: *httpx.router.Context) anyerror!httpx.router.Response {
const htmlContent =
\\<!DOCTYPE html>
\\<html>
\\<head>
\\ <title>Live Reload Demo</title>
\\ <link rel="stylesheet" href="/style.css">
\\</head>
\\<body>
\\ <h1>Live Reload with HTTPX</h1>
\\ <p>Modify files to see instant reload.</p>
\\</body>
\\</html>
;
return ctx.html(htmlContent);
}
fn styleHandler(_: *httpx.router.Context) anyerror!httpx.router.Response {
return .{
.status = 200,
.body = "body { background: #1e1e2e; color: #cdd6f4; font-family: sans-serif; }",
.contentType = "text/css; charset=utf-8",
};
}
pub fn main() !void {
var gpa: std.heap.DebugAllocator(.{}) = .init;
defer _ = gpa.deinit();
const allocator = gpa.allocator();
const io = std.Io.Threaded.global_single_threaded.io();
std.debug.print("==> HTTPX Live Reload Server Demo\n\n", .{});
var server = try httpx.Server.init(allocator, io, .{
.host = "127.0.0.1",
.port = 0,
.enableDocs = false,
.maxConnections = 4,
});
defer server.deinit();
try server.get("/", indexHandler);
try server.get("/style.css", styleHandler);
const port = server.localPort();
std.debug.print("Server listening on http://127.0.0.1:{d}\n", .{port});
const ServerThread = struct {
fn run(s: *httpx.Server) void {
s.run();
}
};
const t = try std.Thread.spawn(.{}, ServerThread.run, .{&server});
defer t.join();
var client = httpx.Client.init(allocator, io, .{});
defer client.deinit();
const rootUrl = try std.fmt.allocPrint(allocator, "http://127.0.0.1:{d}/", .{port});
defer allocator.free(rootUrl);
var res = try client.get(rootUrl, .{});
defer res.deinit();
std.debug.print("GET / returned status {d} (Content-Type: {s})\n", .{ res.status, res.contentType() });
var doc = try res.html();
defer doc.deinit();
std.debug.print("Parsed Page Title: '{s}'\n", .{try doc.title()});
std.debug.print("\nLive reload server verification successful.\n", .{});
server.stop();
}