diff --git a/README.md b/README.md index 41fe991..ed97f0d 100644 --- a/README.md +++ b/README.md @@ -186,6 +186,18 @@ app.serve("mystaticfolder", "/public"); // A GET request to /public/test.txt would serve the local file at mystaticfolder/test.txt ``` +(Optional) Static route with default index page + +You could define a default index page for your static routes such as `index.html` + +```typescript +app.serve("mystaticfolder", "/", { + index: "index.html", +}); +``` + +so when a user requests `/`, the server will serve the file `mystaticfolder/index.html` + ### Regex paths You can provide a RegExp object instead of a string and receive the matches. diff --git a/aqua.ts b/aqua.ts index e407127..2afdb20 100644 --- a/aqua.ts +++ b/aqua.ts @@ -139,6 +139,7 @@ type RoutingSchema = { export interface RoutingOptions { schema?: RoutingSchema; + index?: string; } export enum MiddlewareType { @@ -401,9 +402,9 @@ export default class Aqua { private async handleStaticRequest( req: Request, - { path, folder }: { path: string; folder: string }, + { path, folder, index }: { path: string; folder: string, index?: string; }, ): Promise { - const requestedPath = parseRequestPath(req.url); + let requestedPath = parseRequestPath(req.url); const resourcePath: string = requestedPath.replace(path, ""); const extension: string = resourcePath.replace( /.*(?=\.[a-zA-Z0-9_]*$)/, @@ -414,6 +415,11 @@ export default class Aqua { : null; try { + + if(index !== "" && index !== undefined && index !== null){ + requestedPath = index; + } + return { headers: contentType ? { "Content-Type": contentType } : undefined, content: await Deno.readFile(`${folder}/${resourcePath}`), @@ -602,8 +608,11 @@ export default class Aqua { this.staticRoutes.push({ folder: folder.replace(/\/$/, "") + "/", path: path.replace(/\/$/, "") + "/", - responseHandler: async (req) => - await this.handleStaticRequest(req, { path, folder }), + responseHandler: async (req) => { + + + return await this.handleStaticRequest(req, { path, folder, index: options.index }); + }, options, }); return this;