Skip to content

Commit

Permalink
added setContentTypeFromFilename thx @hauleth.
Browse files Browse the repository at this point in the history
  • Loading branch information
renerocksai committed Jan 9, 2024
1 parent 295c2f6 commit 290d8bd
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
1 change: 1 addition & 0 deletions examples/hello_json/hello_json.zig
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ fn on_request(r: zap.Request) void {
}
std.debug.print("<< json: {s}\n", .{json_to_send});
r.setContentType(.JSON) catch return;
r.setContentTypeFromFilename("test.json") catch return;
r.sendBody(json_to_send) catch return;
}
}
Expand Down
20 changes: 19 additions & 1 deletion src/zap.zig
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ pub const Request = struct {
return self.setHeader("content-type", s);
}

/// Tries to determine the content type by file extension, and sets it.
/// Tries to determine the content type by file extension of request path, and sets it.
pub fn setContentTypeFromPath(self: *const Self) !void {
const t = fio.http_mimetype_find2(self.h.*.path);
if (fio.is_invalid(t) == 1) return error.HttpSetContentType;
Expand All @@ -245,6 +245,24 @@ pub const Request = struct {
if (ret == -1) return error.HttpSetContentType;
}

/// Tries to determine the content type by filename extension, and sets it.
/// If the extension cannot be determined, NoExtensionInFilename error is
/// returned.
pub fn setContentTypeFromFilename(self: *const Self, filename: []const u8) !void {
const ext = std.fs.path.extension(filename);

if (ext.len > 1) {
var e = ext[1..];
var obj = fio.http_mimetype_find(@constCast(e.ptr), e.len);

if (util.fio2str(obj)) |mime_str| {
try self.setHeader("content-type", mime_str);
}
} else {
return error.NoExtensionInFilename;
}
}

/// Returns the header value of given key name. Returned mem is temp.
/// Do not free it.
pub fn getHeader(self: *const Self, name: []const u8) ?[]const u8 {
Expand Down

0 comments on commit 290d8bd

Please sign in to comment.