Single file static hosting

This commit is contained in:
MatthiasSaihttam 2021-08-28 20:02:41 -04:00
parent 4c5985e0ff
commit f4408190f0
3 changed files with 22 additions and 14 deletions

View File

@ -82,16 +82,17 @@ export default class GeminiServer {
for (const p of this.pathRegistry) {
//TODO: Wildcard hostnames
if (p.hostname === socket.servername) {
//If the requested path is a sub path (e.g. equal to or more specific than the path in the current registry entry)
const isSubPath = !path.posix.relative(p.path, url.pathname).startsWith("..");
if (path.posix.resolve(url.pathname) === p.path) {
console.log(p.handler);
// console.log(p.handler instance);
const res = p.handler.handle(url);
socket.write(res);
socket.end();
return;
if (p.handler.matchesSubpaths) {
//If the requested path is a sub path (e.g. equal to or more specific than the path in the current registry entry)
const isSubPath = !path.posix.relative(p.path, url.pathname).startsWith("..");
console.log(isSubPath);
}else {
if (path.posix.resolve(url.pathname) === p.path) {
const res = p.handler.handle(url, p.path);
socket.write(res);
socket.end();
return;
}
}
}
}

View File

@ -37,7 +37,7 @@ server.registerPath("MacBookGamma.local/", "### Hello from my Mac!");
// We provide some convenient handlers for static, CGI, and reverse proxy
//if the passed file is a single file, it's a file. If it's a directory, all sub-files are auto-included
server.registerPath("localhost/static", new StaticHandler("/tmp/files " /*, {options}*/));
server.registerPath("localhost/static/about.gmi", new StaticHandler("/tmp/content/about.gmi" /*, {options}*/));
//The file passed to CGI handler must exist and be executable at run time
//You know what, CGIHandler hashes the file

View File

@ -9,13 +9,20 @@ export default class StaticHandler extends DefaultHandler {
constructor(basePath) {
super();
this.isSingleFile = true;
this.basePath = basePath;
//This will throw if the file is a directory or doesn't exist
fs.readFileSync(this.basePath);
this.matchesSubpaths = !this.isSingleFile;
}
// This is the handler
handle (url) {
handle (url, p) {
const relativePath = path.relative(p, url.pathname);
//Concat and normalize the passed URL as being relative to the base path
const toServe = path.join(this.basePath, url.pathname);
const toServe = path.join(this.basePath, relativePath);
//If the resulting path is a parent, relative to basePath, disallow that
if (path.relative(this.basePath, toServe).startsWith("..")) {
return "50"
@ -24,6 +31,6 @@ export default class StaticHandler extends DefaultHandler {
//TODO: import mmmagic
//TODO: convert line endings
const data = fs.readFileSync(toServe);
return "20 text/plain\r\n" + data;
return "20 text/gemini\r\n" + data;
}
}