commit 7948a965f9fadc2b36d840de4f2aa626a5b2b2a4
parent eaabd5de6c01554038efe86b999a356ced915963
Author: quantumish <freifeld.david@gmail.com>
Date: Wed, 12 Apr 2023 19:58:28 -0700
Further core logic cleanups
Diffstat:
3 files changed, 26 insertions(+), 22 deletions(-)
diff --git a/http.c b/http.c
@@ -24,6 +24,16 @@
#include "http/response.h"
#include "http/request.h"
+
+response_t serve_error(enum StatusCode c) {
+ response_t r = resp_new(c);
+ resp_add_hdr(&r, "Content-Type", "text/html");
+ char msg[32] = {0};
+ sprintf(msg, "<h1>Error %d</h1>", c);
+ resp_add_content(&r, msg, strlen(msg));
+ return r;
+}
+
shitvec_t paths;
response_t serve_file(request_t req) {
@@ -38,8 +48,20 @@ response_t serve_file(request_t req) {
for (size_t i = 0; read(fd, fbuf+(i*4096), 4096) > 0; i++);
char* ext = strchr(req.path, '.'); // NOTE breaks if there's a dir with a dot...
+
resp_set_ctype(&r, ext);
-
+
+ bool ok = false;
+ char* mtype = (char*)ext_to_mtype(ext);
+ for (int i = 0; i < req.headers.vec_sz; i++) {
+ char* item = shitvec_get(&req.headers, i);
+ if (strcmp(item, ext) == 0 || strcmp(item, "*/*") == 0) {
+ ok = true;
+ break;
+ }
+ }
+ if (!ok) return serve_error(NotAcceptable);
+
char datebuf[64];
time_to_str(st.st_mtim.tv_sec, datebuf);
resp_add_hdr(&r, "Last-Modified", datebuf);
@@ -63,16 +85,6 @@ response_t serve_file(request_t req) {
return r;
}
-response_t serve_error(enum StatusCode c) {
- response_t r = resp_new(c);
- resp_add_hdr(&r, "Content-Type", "text/html");
- char msg[32] = {0};
- sprintf(msg, "<h1>Error %d</h1>", c);
- resp_add_content(&r, msg, strlen(msg));
- return r;
-}
-
-
// TODO actually respect requests
// TODO handle gzip
// TODO list dirs
diff --git a/http/response.c b/http/response.c
@@ -57,15 +57,5 @@ const char* ext_to_mtype(char* ext) {
}
void resp_set_ctype(response_t* r, char* ext) {
- if (ext == NULL) {
- resp_add_hdr(r, "Content-Type", "text/plain");
- } else if (strcmp(ext+1, "html") == 0) {
- resp_add_hdr(r, "Content-Type", "text/html");
- } else if (strcmp(ext+1, "png") == 0) {
- resp_add_hdr(r, "Content-Type", "image/png");
- } else if (strcmp(ext+1, "svg") == 0) {
- resp_add_hdr(r, "Content-Type", "image/svg+xml");
- } else if (strcmp(ext+1, "jpeg") == 0) {
- resp_add_hdr(r, "Content-Type", "image/jpeg");
- }
+ resp_add_hdr(r, "Content-Type", (char*)ext_to_mtype(ext));
}
diff --git a/http/response.h b/http/response.h
@@ -42,6 +42,8 @@ typedef struct response {
size_t sz;
} response_t;
+const char* ext_to_mtype(char* ext);
+
response_t __resp_new(enum StatusCode code, char* code_name);
#define resp_new(code) __resp_new(code, STRINGIZE(code))