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 / 06_middleware.zig
2.3 kB 63 lines
1const std = @import("std"); 2const httpz = @import("httpz"); 3const Logger = @import("middleware/Logger.zig"); 4 5const Allocator = std.mem.Allocator; 6 7const PORT = 8806; 8 9// This example show how to use and create middleware. There's overlap between 10// what you can achieve with a custom dispatch function and per-route 11// configuration (shown in the next example) and middleware. 12// see 13 14// See middleware/Logger.zig for an example of how to write a middleware 15 16pub fn main(init: std.process.Init) !void { 17 const allocator = init.gpa; 18 19 var server = try httpz.Server(void).init(init.io, allocator, .{ .address = .localhost(PORT) }, {}); 20 21 defer server.deinit(); 22 23 // ensures a clean shutdown, finishing off any existing requests 24 // see 09_shutdown.zig for how to to break server.listen with an interrupt 25 defer server.stop(); 26 27 // creates an instance of the middleware with the given configuration 28 // see example/middleware/Logger.zig 29 const logger = try server.middleware(Logger, .{ .io = init.io, .query = true }); 30 31 var router = try server.router(.{}); 32 33 // Apply middleware to all routes created from this point on 34 router.middlewares = &.{logger}; 35 36 router.get("/", index, .{}); 37 router.get("/other", other, .{ .middlewares = &.{}, .middleware_strategy = .replace }); 38 39 std.debug.print("listening http://localhost:{d}/\n", .{PORT}); 40 41 // Starts the server, this is blocking. 42 try server.listen(); 43} 44 45fn index(_: *httpz.Request, res: *httpz.Response) !void { 46 res.content_type = .HTML; 47 res.body = 48 \\<!DOCTYPE html> 49 \\<p>There's overlap between a custom dispatch function and middlewares. 50 \\<p>This page includes the example Logger middleware, so requesting it logs information. 51 \\<p>The <a href="/other">other</a> endpoint uses a custom route config which 52 \\ has no middleware, effectively disabling the Logger for that route. 53 ; 54} 55 56fn other(_: *httpz.Request, res: *httpz.Response) !void { 57 // Called with a custom config which had no middlewares 58 // (effectively disabling the logging middleware) 59 res.body = 60 \\ Accessing this endpoint will NOT generate a log line in the console, 61 \\ because the Logger middleware is disabled. 62 ; 63}