@@ -1,7 +1,9 @@
const std = @import("std");
const Allocator = std.mem.Allocator;
const indexOf = std.mem.indexOf;
const indexOfScalar = std.mem.indexOfScalar;
const eql = std.mem.eql;
const allocPrint = std.fmt.allocPrint;
const Headers = @import("headers.zig");
const Cookies = @import("cookies.zig");
@@ -12,11 +14,16 @@ pub const Request = @This();
/// TODO this is unstable and likely to be removed
raw: RawReq,
/// Default API, still unstable, but unlike to drastically change
headers: Headers,
uri: []const u8,
method: Methods,
cookie_jar: Cookies.Jar,
/// Unstable API; likely to exist in some form, but might be changed
remote_addr: RemoteAddr,
pub const RawReq = union(enum) {
zwsgi: *zWSGIRequest,
http: *std.http.Server.Request,
@@ -27,6 +34,8 @@ const Pair = struct {
val: []const u8,
};
pub const RemoteAddr = []const u8;
pub const Methods = enum(u8) {
GET = 1,
HEAD = 2,
@@ -51,17 +60,19 @@ pub fn initZWSGI(a: Allocator, zwsgi: *zWSGIRequest) !Request {
var req = Request{
.raw = .{ .zwsgi = zwsgi },
.headers = Headers.init(a),
.uri = undefined,
.method = Methods.GET,
.uri = undefined,
.cookie_jar = undefined,
.remote_addr = undefined,
};
for (zwsgi.vars) |v| {
try req.addHeader(v.key, v.val);
if (eql(u8, v.key, "PATH_INFO")) {
req.uri = v.val;
}
if (eql(u8, v.key, "REQUEST_METHOD")) {
} else if (eql(u8, v.key, "REQUEST_METHOD")) {
req.method = Methods.fromStr(v.val) catch Methods.GET;
} else if (eql(u8, v.key, "REMOTE_ADDR")) {
req.remote_addr = v.val;
}
}
req.cookie_jar = try Cookies.Jar.initFromHeaders(a, &req.headers);
@@ -79,12 +90,21 @@ pub fn initHttp(a: Allocator, http: *std.http.Server.Request) !Request {
else => @panic("not implemented"),
},
.cookie_jar = undefined,
.remote_addr = undefined,
};
var itr = http.iterateHeaders();
while (itr.next()) |head| {
try req.addHeader(head.name, head.value);
}
req.cookie_jar = try Cookies.Jar.initFromHeaders(a, &req.headers);
const ipport = try allocPrint(a, "{}", .{http.server.connection.address});
if (indexOfScalar(u8, ipport, ':')) |i| {
req.remote_addr = ipport[0..i];
try req.addHeader("REMOTE_ADDR", req.remote_addr);
try req.addHeader("REMOTE_PORT", ipport[i + 1 ..]);
} else @panic("invalid address from http server");
return req;
}