Public
HTTP (deprecated)
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Readme

Hello world server, using http functions.

Try hitting URLs such as: /world, /world.txt, /world.json, /world.html, or even /<script>.html.

This demonstrates how you can import and compose simple functions to construct a router to route based on various aspects of a request, ie. the URL path, method, and even on media-types based on path extension or the Accept header.

See routing functions, and response helpers on JSR.

For a more detailed guide on building a Deno app, including things like fs based routing, with these fns see... https://jollytoad.deno.dev/blog/http_getting_started

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import { html } from "jsr:@http/response/html";
import { json } from "jsr:@http/response/json";
import { ok } from "jsr:@http/response/ok";
import { seeOther } from "jsr:@http/response/see-other";
import { byMediaType } from "jsr:@http/route/by-media-type";
import { byMethod } from "jsr:@http/route/by-method";
import { byPattern } from "jsr:@http/route/by-pattern";
import { handle } from "jsr:@http/route/handle";
import { escape } from "jsr:@std/html/entities";
export default handle([
byPattern(
"/:name{.:ext}?",
byMethod({
GET: byMediaType({
"text/html": (req, match) =>
html(`<!DOCTYPE html>\n<h1>Hello ${escape(decodeURIComponent(match.pathname.groups.name))}</h1>`),
"text/plain": (req, match) => ok(`Hello ${decodeURIComponent(match.pathname.groups.name)}`),
"application/json": (req, match) => json({ hello: decodeURIComponent(match.pathname.groups.name) }),
}),
}),
),
() => {
return seeOther("/world");
},
]);
jollytoad-helloworld.web.val.run
June 28, 2024