Add new context object

This commit is contained in:
jaina heartles 2022-05-23 21:52:34 -07:00
parent c141d537c8
commit 004568a907
2 changed files with 89 additions and 76 deletions

View file

@ -153,7 +153,7 @@ fn handleHttpRequest(reader: Reader, writer: Writer, handler: Handler) anyerror!
const headers = try parseHeaders(allocator, reader);
const has_body = (headers.get("Content-Length") orelse headers.get("Transfer-Encoding")) != null;
const has_body = method.requestHasBody() and headers.get("Content-Length") != null;
const tfer_encoding = headers.get("Transfer-Encoding");
if (tfer_encoding != null and !std.mem.eql(u8, tfer_encoding.?, "identity")) {
@ -165,34 +165,52 @@ fn handleHttpRequest(reader: Reader, writer: Writer, handler: Handler) anyerror!
return error.UnsupportedMediaType;
}
var context = Context{
.request = .{
var ctx = Context{
.request = Request2{
.method = method,
.path = path,
.headers = headers,
.body = if (has_body) reader else null,
},
.response = .{
.headers = HeaderMap.init(allocator),
.writer = writer,
},
.allocator = allocator,
};
try handler(&context);
if (has_body) {
const body_len = std.fmt.parseInt(usize, headers.get("Content-Length").?, 10) catch return error.BadRequest;
const body = try allocator.alloc(u8, body_len);
errdefer allocator.free(body);
if ((try reader.read(body)) != body_len) return error.BadRequest;
ctx.request.body = body;
}
defer if (has_body) allocator.free(ctx.request.body.?);
_ = ctx;
//try handler(&ctx);
_ = handler;
_ = writer;
_ = path;
}
pub const Context = struct {
const Request = struct {
request: Request2,
allocator: std.mem.Allocator,
};
pub const Response2 = struct {
status: Status,
headers: HeaderMap,
body: ?[]const u8 = null,
};
pub const Request2 = struct {
method: Method,
path: []const u8,
headers: HeaderMap,
body: ?[]const u8 = null,
};
body: ?Reader,
};
const Response = struct {
const Response = struct {
headers: HeaderMap,
writer: Writer,
@ -244,9 +262,4 @@ pub const Context = struct {
pub fn statusOnly(self: *Response, status: u16) !void {
try self.openInternal(status);
}
};
request: Request,
response: Response,
allocator: std.mem.Allocator,
};

View file

@ -11,8 +11,8 @@ pub const ciutf8 = util.ciutf8;
//pub const io_mode = .evented;
pub const router = routing.makeRouter(*http.Context, &[_]routing.RouteFn(*http.Context){
routing.makeRoute(.GET, "/", staticString("Index Page")),
routing.makeRoute(.GET, "/abc", staticString("abc")),
//routing.makeRoute(.GET, "/", staticString("Index Page")),
//routing.makeRoute(.GET, "/abc", staticString("abc")),
//routing.makeRoute(.GET, "/user/:id", getUser),
//routing.makeRoute(.POST, "/note/", postNote),
});