srctree

Gregory Mullen parent e1bf8473 5c2af8ec
refactor and test uri iterator

src/frame.zig added: 34, removed: 7, total 27
@@ -5,7 +5,7 @@ downstream: union(Downstream) {
zwsgi: Stream,
http: Stream,
},
uri: UriIter,
uri: Router.UriIterator,
 
// TODO fix this unstable API
auth: Auth.Provider,
@@ -71,7 +71,6 @@ pub const RouteData = struct {
};
 
pub fn init(a: Allocator, req: *const Request) !Frame {
std.debug.assert(req.uri[0] == '/');
return .{
.alloc = a,
.request = req,
@@ -79,7 +78,7 @@ pub fn init(a: Allocator, req: *const Request) !Frame {
.zwsgi => |z| .{ .zwsgi = z.*.conn.stream },
.http => .{ .http = req.raw.http.server.connection.stream },
},
.uri = splitScalar(u8, req.uri[1..], '/'),
.uri = try splitUri(req.uri),
.auth = Auth.InvalidAuth.provider(),
.headers = Headers.init(a),
.cookie_jar = try Cookies.Jar.init(a),
@@ -355,7 +354,7 @@ const Request = @import("request.zig");
const RequestData = @import("request_data.zig");
const Template = @import("template.zig");
const Router = @import("router.zig");
const UriIter = Router.UriIter;
const splitUri = Router.splitUri;
 
const Headers = @import("headers.zig");
const Auth = @import("auth.zig");
 
src/router.zig added: 34, removed: 7, total 27
@@ -26,7 +26,7 @@ pub const RouterFn = *const fn (*Frame, RouteFn) BuildFn;
const Router = @This();
 
/// TODO document
pub const UriIter = std.mem.SplitIterator(u8, .scalar);
pub const UriIterator = std.mem.SplitIterator(u8, .scalar);
 
/// The Verse router will scan through an array of Match structs looking for a
/// given name. Verse doesn't assert that the given name will match a director
@@ -342,6 +342,15 @@ pub fn defaultBuilder(vrs: *Frame, build: BuildFn) void {
};
}
 
pub fn splitUri(uri: []const u8) !UriIterator {
if (uri.len == 0 or uri[0] != '/') return error.InvalidUri;
return .{
.index = 0,
.buffer = uri[1..],
.delimiter = '/',
};
}
 
const root = [_]Match{
ROUTE("", default),
};
@@ -370,6 +379,25 @@ pub fn testingRouter(frame: *Frame) RoutingError!BuildFn {
return router(frame, &root);
}
 
test "uri" {
const uri_file = "/root/first/second/third";
const uri_dir = "/root/first/second/";
 
var itr = try splitUri(uri_file);
try std.testing.expectEqualStrings("root", itr.next().?);
try std.testing.expectEqualStrings("first", itr.next().?);
try std.testing.expectEqualStrings("second", itr.next().?);
try std.testing.expectEqualStrings("third", itr.next().?);
try std.testing.expectEqual(null, itr.next());
 
itr = try splitUri(uri_dir);
try std.testing.expectEqualStrings("root", itr.next().?);
try std.testing.expectEqualStrings("first", itr.next().?);
try std.testing.expectEqualStrings("second", itr.next().?);
try std.testing.expectEqualStrings("", itr.next().?);
try std.testing.expectEqual(null, itr.next());
}
 
const std = @import("std");
const log = std.log.scoped(.Verse);
const Allocator = std.mem.Allocator;