danteissaias/fast

Serve static

Closed this issue · 2 comments

I really like the simplicity of this framework. Though I wonder if a built-in method for serving static files could reduce some boilerplate code. Here's a quick example:

// A request to /style/test.css will serve a file located in /base/style/test.css

import { contentType } from "https://deno.land/std/media_types/mod.ts";
import { join, extname } from "https://deno.land/std/path/mod.ts";

server.get('/style/*', async({ request, redirect }) => {
	const base_directory = 'base';

	try {
		const { pathname } = new URL(request.url);
		const file_url = join(base_directory, pathname);
		const file_type = contentType(extname(file_url)) || "application/octet-stream";
		const file_stats = await Deno.stat(file_url);
		const file_content = await Deno.open(file_url);

		return new Response(file_content.readable, {
			headers: new Headers({
				'content-type': file_type,
				'content-length': file_stats.size,
			})
		});
	} catch(error) {
		return new Response(null, {
			status: error instanceof Deno.errors.NotFound ? 404 : 500
		});
	}
});

which API-wise could be reduced to:

server.static('/style/*', 'base');

I’ll look into adding this soon.

Added in 87cd60f