Examples
server
The sources of the example, as they are at the commit this site was built from. Examples says what each example is about, and the playground runs a text of the language in the page.
#main.sts
// A web server: functions handed to the outside, values of the outside, and promises.
extern "node:http" {
type Server
type IncomingMessage
type ServerResponse
function createServer(handler: (request: IncomingMessage, response: ServerResponse) => void): Server
function Server.listen(port: number): Server
function Server.close(): Server
const IncomingMessage.url: Option<string>
function ServerResponse.setHeader(name: string, value: string): ServerResponse
function ServerResponse.end(body: string): ServerResponse
}
extern {
type Response
function fetch(url: string): Promise<Response>
function Response.text(): Promise<string>
const Response.status: number
}
type Reply = { status: number, body: string }
export function route(path: string): Reply {
match path.split("/").filter(part => part.length > 0) {
parts => match parts[0] {
None => { status: 200, body: "home" },
Some("hello") => { status: 200, body: `Hello, ${parts[1] ?? "you"}!` },
Some(other) => { status: 404, body: `nothing at /${other}` },
},
}
}
function answer(request: IncomingMessage, response: ServerResponse) {
const reply = route(request.url.unwrapOr(None) ?? "/")
const sent = response.setHeader("content-type", "text/plain").andThen(ready => ready.end(reply.body))
match sent {
Ok(_) => {},
Err(thrown) => console.error(`could not answer: ${thrown.message}`),
}
}
async function get(url: string): Promise<Result<string, string>> {
const response = (await fetch(url)).mapErr(thrown => thrown.message)?
(await response.text()).mapErr(thrown => thrown.message)
}
export async function main(args: string[]): Promise<Result<void, string>> {
const port = (args[0] ?? "8123").toNumber().okOr("the port is a number")?
const server = createServer(answer).andThen(made => made.listen(port)).mapErr(thrown => thrown.message)?
console.log(await get(`http://localhost:${port}/hello/Ada`)?)
console.log(await get(`http://localhost:${port}/nowhere`)?)
server.close().map(closed => {}).mapErr(thrown => thrown.message)
}