Commit a38e81866c4caf8413329e4d6b792a1bab9a6a57

Baptiste 2024-08-06T21:39:00

httpd: directory

diff --git a/lib/kc3/0.1/httpd.kc3 b/lib/kc3/0.1/httpd.kc3
index 4ebbc62..9e58885 100644
--- a/lib/kc3/0.1/httpd.kc3
+++ b/lib/kc3/0.1/httpd.kc3
@@ -1,5 +1,7 @@
 defmodule HTTPd do
 
+  def root_dir = "."
+
   def server = fn (host, port) {
     socket = Socket.listen(host, port)
     puts("KC3 HTTPd: listening on #{host}:#{port}")
@@ -15,11 +17,8 @@ defmodule HTTPd do
     puts("HTTPd.server_loop: got client #{client}")
     req = HTTP.Request.buf_parse(client.buf_rw.r)
     if req do
-      puts("HTTPd.server_loop: got request #{req}")
       router = route_request(req)
-      puts("HTTPd.server_loop: router: #{router}")
       res = router(req)
-      puts("HTTPd.server_loop: response: #{res}")
       HTTP.Response.buf_write(res, client.buf_rw.w)
     end
   }
@@ -78,12 +77,35 @@ defmodule HTTPd do
     %HTTP.Response{code: 404, body: body}
   }
 
-  def root_dir = "."
+  def directory_page = fn (request) {
+    files = File.list(root_dir + request.url)
+    file_li = fn (file) {
+      slash = if request.url == "/" do "" else "/" end
+      "<li><a href=\"#{request.url}#{slash}#{file}\">#{request.url}#{slash}#{file}</a></li>"
+    }
+    body = "<html>
+  <head>
+    <title>Index of #{request.url}</title>
+  </head>
+  <body>
+    <h1>Index of #{request.url}</h1>
+    <ul>
+      #{str(List.map(files, file_li))}
+    </ul>
+  </body>
+</html>
+"
+    %HTTP.Response{body: body}
+  }
 
   def route_request = fn (request) {
     path = root_dir + request.url
     if File.exists?(path) do
-      debug_page
+      if File.is_directory?(path) do
+        directory_page
+      else
+        debug_page
+      end
     else
       error_404_page
     end
diff --git a/libkc3/str.c b/libkc3/str.c
index 8226538..aa4a64a 100644
--- a/libkc3/str.c
+++ b/libkc3/str.c
@@ -258,6 +258,8 @@ s_str * str_init_cast (s_str *str, const s_sym * const *type,
     return str_init_bool(str, tag->data.bool);
   case TAG_CHARACTER:
     return str_init_character(str, tag->data.character);
+  case TAG_FN:
+    return str_init_fn(str, &tag->data.fn);
   case TAG_MAP:
     return str_init_map(str, &tag->data.map);
   case TAG_PTR:
@@ -430,6 +432,7 @@ s_str * str_init_f (s_str *str, const char *fmt, ...)
   return str;
 }
 
+DEF_STR_INIT_STRUCT(fn)
 DEF_STR_INIT_STRUCT(map)
 DEF_STR_INIT(ptr, u_ptr_w)
 DEF_STR_INIT(ptr_free, u_ptr_w)
diff --git a/libkc3/str.h b/libkc3/str.h
index a0c0136..c203cda 100644
--- a/libkc3/str.h
+++ b/libkc3/str.h
@@ -53,6 +53,7 @@ s_str * str_init_copy (s_str *str, const s_str *src);
 s_str * str_init_copy_1 (s_str *str, const char *p);
 s_str * str_init_empty (s_str *str);
 s_str * str_init_f (s_str *str, const char *fmt, ...);
+PROTOTYPE_STR_INIT_STRUCT(fn);
 PROTOTYPE_STR_INIT_STRUCT(map);
 PROTOTYPE_STR_INIT(ptr, u_ptr_w);
 PROTOTYPE_STR_INIT(ptr_free, u_ptr_w);