An HTTP/1.1 server for zig
0

Configure Feed

Select the types of activity you want to include in your feed.

http.zig / examples / 11_html_streaming.zig
1.6 kB 54 lines
1const std = @import("std"); 2const httpz = @import("httpz"); 3const Allocator = std.mem.Allocator; 4 5const PORT = 8801; 6 7/// This example demonstrates HTML streaming. 8pub fn main(init: std.process.Init) !void { 9 const allocator = init.gpa; 10 11 var server = try httpz.Server(void).init(init.io, allocator, .{ 12 .address = .localhost(PORT), 13 }, {}); 14 defer server.deinit(); 15 16 // ensures a clean shutdown, finishing off any existing requests 17 // see 09_shutdown.zig for how to to break server.listen with an interrupt 18 defer server.stop(); 19 20 var router = try server.router(.{}); 21 22 router.get("/", index, .{}); 23 24 std.debug.print("listening http://localhost:{d}/\n", .{PORT}); 25 26 // Starts the server, this is blocking. 27 try server.listen(); 28} 29 30fn index(_: *httpz.Request, res: *httpz.Response) !void { 31 32 try res.chunk( 33 \\<!DOCTYPE html> 34 \\<html> 35 \\ <body> 36 \\ <template shadowrootmode="open"> 37 \\ <ul> 38 \\ <li><slot name="item-0">Loading...</slot></li> 39 \\ <li><slot name="item-1">Loading...</slot></li> 40 \\ <li><slot name="item-2">Loading...</slot></li> 41 \\ </ul> 42 \\ </template> 43 \\ </body> 44 \\</html> 45 ); 46 47 const io = res.conn.io; 48 try io.sleep(.fromSeconds(1), .awake); 49 try res.chunk("\n<span slot='item-2'>Item 2</span>"); 50 try io.sleep(.fromSeconds(1), .awake); 51 try res.chunk("\n<span slot='item-0'>Item 0</span>"); 52 try io.sleep(.fromSeconds(1), .awake); 53 try res.chunk("\n<span slot='item-1'>Item 1</span>"); 54}