1 #include <msp/core/application.h>
2 #include <msp/debug/demangle.h>
3 #include <msp/fs/dir.h>
4 #include <msp/fs/path.h>
5 #include <msp/fs/utils.h>
6 #include <msp/http/request.h>
7 #include <msp/http/response.h>
8 #include <msp/http/server.h>
9 #include <msp/io/eventdispatcher.h>
10 #include <msp/io/file.h>
11 #include <msp/io/print.h>
12 #include <msp/strings/utils.h>
17 class MiniHttpd: public RegisteredApplication<MiniHttpd>
22 IO::EventDispatcher event_disp;
25 MiniHttpd(int, char **);
30 void request(const Http::Request &, Http::Response &);
33 MiniHttpd::MiniHttpd(int argc, char **argv):
39 server.signal_request.connect(sigc::mem_fun(this, &MiniHttpd::request));
40 server.use_event_dispatcher(&event_disp);
43 void MiniHttpd::tick()
48 void MiniHttpd::request(const Http::Request &req, Http::Response &resp)
50 IO::print("%s requests \"%s\"\n", req.get_header("-Client-Host"), c_escape(req.get_path()));
52 FS::Path path = root/req.get_path().substr(1);
53 if(FS::descendant_depth(path, root)<0)
55 resp = Http::Response(Http::FORBIDDEN);
56 resp.add_content("You do not have permission to access the requested resource\n");
62 IO::BufferedFile file(path.str());
63 resp = Http::Response(Http::OK);
64 if(FS::extpart(path.str())==".html")
65 resp.set_header("Content-Type", "text/html");
69 unsigned len = file.read(buf, sizeof(buf));
72 resp.add_content(string(buf, len));
75 catch(const IO::file_not_found &)
77 resp = Http::Response(Http::NOT_FOUND);
78 resp.add_content("The requested resource was not found\n");
80 catch(const exception &e)
82 resp = Http::Response(Http::INTERNAL_ERROR);
83 resp.add_content(format("An exception occurred while trying to retrieve %s:\n", req.get_path()));
84 resp.add_content(format(" type: %s\n", Debug::demangle(typeid(e).name())));
85 resp.add_content(format(" what(): %s\n", e.what()));
89 resp = Http::Response(Http::INTERNAL_ERROR);
90 resp.add_content("Something horrible happened and I can't even tell what it was!\n");