Supported more MIME types.

This commit is contained in:
yhirose 2017-05-14 00:46:40 -04:00
parent 5873e360a6
commit f3eb1c4e00

View File

@ -406,24 +406,47 @@ inline void read_file(const std::string& path, std::string& out)
fs.read(&out[0], size); fs.read(&out[0], size);
} }
inline std::string get_file_extension(const std::string& path) inline std::string file_extension(const std::string& path)
{ {
std::smatch m; std::smatch m;
auto pat = std::regex("\\.([a-zA-Z0-9]+)$"); auto pat = std::regex("\\.([a-zA-Z0-9]+)$");
auto ret = std::regex_search(path, m, pat); if (std::regex_search(path, m, pat)) {
std::string content_type;
if (ret) {
return m[1].str(); return m[1].str();
} }
return std::string(); return std::string();
} }
inline const char* get_content_type_from_file_extension(const std::string& ext) inline const char* content_type(const std::string& path)
{ {
if (ext == "html") { auto ext = detail::file_extension(path);
if (ext == "txt") {
return "text/plain";
} else if (ext == "html") {
return "text/html"; return "text/html";
} else if (ext == "js") {
return "text/javascript";
} else if (ext == "css") {
return "text/css";
} else if (ext == "xml") {
return "text/xml";
} else if (ext == "jpeg" || ext == "jpg") {
return "image/jpg";
} else if (ext == "png") {
return "image/png";
} else if (ext == "gif") {
return "image/gif";
} else if (ext == "svg") {
return "image/svg+xml";
} else if (ext == "ico") {
return "image/x-icon";
} else if (ext == "json") {
return "application/json";
} else if (ext == "pdf") {
return "application/pdf";
} else if (ext == "xhtml") {
return "application/xhtml+xml";
} }
return "text/plain"; return nullptr;
} }
inline const char* status_message(int status) inline const char* status_message(int status)
@ -895,9 +918,10 @@ inline bool Server::handle_file_request(Request& req, Response& res)
if (detail::is_file(path)) { if (detail::is_file(path)) {
detail::read_file(path, res.body); detail::read_file(path, res.body);
res.set_header("Content-Type", auto type = detail::content_type(path);
detail::get_content_type_from_file_extension( if (type) {
detail::get_file_extension(path))); res.set_header("Content-Type", type);
}
res.status = 200; res.status = 200;
return true; return true;
} }