Commit 5a5a957df92101bb401bc3efb8cca9af5ce51fa9

Baptiste 2024-07-25T19:29:19

http_request_buf_parse

diff --git a/http/http.c b/http/http.c
index 645a439..2775347 100644
--- a/http/http.c
+++ b/http/http.c
@@ -14,3 +14,50 @@
 #include "http.h"
 #include "socket.h"
 
+s_http_request * http_request_buf_parse (s_http_request *req, s_buf *buf)
+{
+  s_str line;
+  sw r;
+  s_buf_save save;
+  s_list **tail;
+  s_http_request tmp = {0};
+  assert(req);
+  assert(buf);
+  buf_save_init(buf, &save);
+  if ((r = buf_read_1(buf, "GET ")) < 0)
+    goto restore;
+  if (r > 0)
+    tmp.method = sym_1("get");
+  if (! tmp.method) {
+    err_puts("http_request_buf_parse: no method");
+    goto restore;
+  }  
+  if ((r = buf_read_until_1_into_str(buf, " ", &tmp.url)) <= 0) {
+    err_puts("http_request_buf_parse: invalid URL");
+    goto restore;
+  }
+  if ((r = buf_read_until_1_into_str(buf, "\r\n", &tmp.protocol)) <= 0) {
+    err_puts("http_request_buf_parse: invalid protocol");
+    goto restore;
+  }
+  tail = &tmp.headers;
+  while (1) {
+    if ((r = buf_read_until_1_into_str(buf, "\r\n", &line)) <= 0) {
+      err_puts("http_request_buf_parse: invalid header");
+      goto restore;
+    }
+    if (line.size == 0)
+      break;
+    *tail = list_new(NULL);
+    (*tail)->tag.type = TAG_STR;
+    (*tail)->tag.data.str = line;
+    tail = &(*tail)->next.data.list;
+  }
+  buf_save_clean(buf, &save);
+  *req = tmp;
+  return req;
+ restore:
+  buf_save_restore_rpos(buf, &save);
+  buf_save_clean(buf, &save);
+  return NULL;
+}
\ No newline at end of file
diff --git a/http/types.h b/http/types.h
index e914894..f598f73 100644
--- a/http/types.h
+++ b/http/types.h
@@ -19,6 +19,7 @@
 /* 1 */
 typedef s32               t_socket;
 typedef struct socket_buf s_socket_buf;
+typedef struct http_request s_http_request;
 
 /* 2 */
 typedef t_socket *p_socket;
@@ -31,4 +32,11 @@ struct socket_buf {
   s_buf_rw buf_rw;
 };
 
+struct http_request {
+  const s_sym *method;
+  s_str url;
+  s_str protocol;
+  s_list *headers;
+};
+
 #endif /* HTTP_TYPES_H */