diff --git a/examples/hello_json/hello_json.zig b/examples/hello_json/hello_json.zig index 8cd348c..d5b2131 100644 --- a/examples/hello_json/hello_json.zig +++ b/examples/hello_json/hello_json.zig @@ -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; } } diff --git a/src/zap.zig b/src/zap.zig index cd825ef..74df9be 100644 --- a/src/zap.zig +++ b/src/zap.zig @@ -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; @@ -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 {