╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╯
211 const Context = struct { 212 io: std.Io, 213 allocator: std.mem.Allocator, 214 host: web.Host, 215 err: *std.Io.Writer, 216 }; 217 218 const handle = struct { 219 fn h(ctx: Context, stream: std.Io.net.Stream) void { 220 defer stream.close(ctx.io); 221 web.handleConnection(ctx.io, ctx.allocator, stream, ctx.host, ctx.err) catch |request_err| { 222 serve_common.logError(ctx.io, ctx.err, "web ui request failed: {s}\n", .{@errorName(request_err)}); 223 }; 224 } 225 }.h; 226 227 serve_common.runListener(io, net_server, tasks, err, "web ui", Context{ 228 .io = io, 229 .allocator = allocator, 230 .host = host, 231 .err = err, 232 }, handle); 233 } 234 235 // what a listener does with a port that is already taken 236 const PortPolicy = enum { 237 exact, 238 // leave it to whoever holds it and take an OS-assigned port instead 239 fallback, 240 }; 241 242 fn listen(io: std.Io, listen_address: ListenAddress, policy: PortPolicy) !std.Io.net.Server { 243 const address = try std.Io.net.IpAddress.parseIp4(listen_address.host, listen_address.port); 244 return switch (policy) { 245 .exact => try address.listen(io, .{}), 246 .fallback => address.listen(io, .{}) catch |listen_err| switch (listen_err) { 247 error.AddressInUse => blk: { 248 const any_port = try std.Io.net.IpAddress.parseIp4(listen_address.host, 0); 249 break :blk try any_port.listen(io, .{}); 250 }, 251 else => |e| return e, 252 }, 253 }; 254 } 255 256 fn parseListenAddress(value: []const u8) !ListenAddress { 257 const colon = std.mem.lastIndexOfScalar(u8, value, ':') orelse return error.InvalidListenAddress; 258 if (colon == 0 or colon + 1 >= value.len) return error.InvalidListenAddress; 259 const port = try std.fmt.parseInt(u16, value[colon + 1 ..], 10); 260 return .{ .host = value[0..colon], .port = port }; 261 } 262