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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
use std
use http
const main = {args
var srv, ann, cmd
cmd = std.optparse(args, &[
.maxargs=0,
.opts = [[.opt='a', .arg="ann", .desc="announce on `ann`"]][:]
])
ann = "tcp!localhost!8080"
for opt : cmd.opts
match opt
| ('a', a): ann = a
| _: std.die("unreachable")
;;
;;
match http.announce(ann)
| `std.Ok s: srv = s
| `std.Err e: std.fatal("unable to announce: {}\n", e)
;;
http.serve(srv, route)
}
const route = {srv, sess, req
std.put("Reading path {}\n", req.url.path)
match req.url.path
| "/ping": respond(srv, sess, 200, "pong")
| "/quit": http.shutdown(srv)
| fspath: showfile(srv, sess, req.url.path)
;;
}
const showfile = {srv, sess, path
var eb : byte[128]
var p
p = std.pathcat(".", path)
match std.slurp(p)
| `std.Ok buf:
respond(srv, sess, 200, buf)
std.slfree(buf)
| `std.Err e:
respond(srv, sess, 404, std.bfmt(eb[:], "error reading {}: {}\n", p, e))
;;
std.slfree(p)
}
const respond = {srv, sess, status, body
var resp
resp = std.mk([
.status=status,
.hdrs = [][:],
.len = 0,
.err = `std.None,
.reason = "",
.body = body,
.enc = `http.Length
])
http.respond(srv, sess, resp)
std.free(resp)
}
|