diff --git a/server.ts b/server.ts index 14aad4d..a203603 100644 --- a/server.ts +++ b/server.ts @@ -1,7 +1,6 @@ -import { contentType } from '@std/media-types' -import { extname } from '@std/path' import { getBaseUrl, getSourceUrl } from './src/url_utils.ts' import { toUser, toUserDomain } from './src/user_utils.ts' +import { serveFile } from './src/serve_file.ts' Deno.serve({ port: Number(Deno.env.get('PORT') ?? 8000) }, async (req) => { const reqUrl = new URL(req.url) @@ -21,20 +20,5 @@ Deno.serve({ port: Number(Deno.env.get('PORT') ?? 8000) }, async (req) => { const fileUrl = getSourceUrl(filePath, baseUrl) // Get source and mime type - const response = await fetch(fileUrl) - const ext = extname(fileUrl.pathname) - const mimeType = contentType(ext) ?? 'text/plain; charset=utf-8' // Assume plain text as default. - - if (response.ok) { - // Update content-type if not bin file - const headers = new Headers(response.headers) - if (headers.get('Content-Type') !== 'application/octet-stream') { - headers.set('Content-Type', mimeType) - } - - // Stream original file to user - return new Response(response.body, { headers }) - } - - return response + return serveFile(fileUrl) }) diff --git a/src/serve_file.ts b/src/serve_file.ts new file mode 100644 index 0000000..e7cba45 --- /dev/null +++ b/src/serve_file.ts @@ -0,0 +1,22 @@ +import { extname } from '@std/path' +import { contentType } from '@std/media-types' + +export async function serveFile(fileUrl: URL): Promise { + // Get source and mime type + const response = await fetch(fileUrl) + const ext = extname(fileUrl.pathname) + const mimeType = contentType(ext) ?? 'text/plain; charset=utf-8' // Assume plain text as default. + + if (response.ok) { + // Update content-type if not bin file + const headers = new Headers(response.headers) + if (headers.get('Content-Type') !== 'application/octet-stream') { + headers.set('Content-Type', mimeType) + } + // Stream original file to user + return new Response(response.body, { headers }) + } + + // Return raw error if status !== 2XX + return response +}