Skip to content

Instantly share code, notes, and snippets.

@pedropalhari
Created January 5, 2021 15:14
Show Gist options
  • Save pedropalhari/a4ac5a17c5548213d2bdaf3d5a23ff1e to your computer and use it in GitHub Desktop.
Save pedropalhari/a4ac5a17c5548213d2bdaf3d5a23ff1e to your computer and use it in GitHub Desktop.
Streaming and static video serving with Deno & Oak
import {
Application,
Router,
send,
} from "https://deno.land/x/[email protected]/mod.ts";
const app = new Application();
const router = new Router();
router
.get("/video", async ({request, response}) => {
const range = request.headers.get("range");
const fileName = "public/Hannibal_1_1.mp4";
const videoSize = (await Deno.stat(fileName)).size;
if (!range) {
response.headers.set("Content-Length", videoSize);
response.headers.set("Content-Type", "video/mp4");
response.body = await Deno.readFile(new URL(fileName, import.meta.url));
}else{
let [start, end] = range.replace(/bytes=/, '').split('-');
start = parseInt(start, 10);
end = end ? parseInt(end, 10) : videoSize - 1;
const maxChunk = 1024 * 1024;
if (((end - start + 1)) > maxChunk) {
end = start + maxChunk - 1;
}
response.headers.set("Content-Range", `bytes ${start}-${end}/${videoSize}`);
response.headers.set("Accept-Ranges", "bytes");
response.headers.set("Content-Length", (end - start) + 1);
let seek;
if(start === 0){
seek = Deno.SeekMode.Start;
}else if(end === videoSize - 1){
seek = Deno.SeekMode.End;
}else{
seek = Deno.SeekMode.Current;
}
const file = await Deno.open(new URL(fileName, import.meta.url), {read: true});
await Deno.seek(file.rid, start, seek);
const content = new Uint8Array(end - start + 1);
await file.read(content);
file.close();
response.type = "video/mp4";
response.status = 206;
response.body = content;
}
});
app.use(router.routes());
app.use(router.allowedMethods());
app.use(async (context) => {
await send(context, context.request.url.pathname, {
index: "index.html",
root: `public`,
});
});
app.listen({
port: 80
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment