-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathbasic.nu
More file actions
75 lines (68 loc) · 1.95 KB
/
basic.nu
File metadata and controls
75 lines (68 loc) · 1.95 KB
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
67
68
69
70
71
72
73
74
75
# basic.nu - A basic HTTP server example for http-nu
#
# Run with: cat examples/basic.nu | http-nu :3001 -
{|req|
match $req.path {
# Home page
"/" => {
let proto = $req.headers.x-forwarded-proto? | default (if ($req.proto | str starts-with "HTTP") { "http" } else { "https" })
let base = $"($proto)://($req.headers.host)($req.mount_prefix? | default '')"
$"<html><body>
<h1>http-nu demo</h1>
<ul>
<li><a href='./hello'>Hello World</a></li>
<li><a href='./json'>JSON Example</a></li>
<li><a href='./echo'>POST Echo</a></li>
<li><a href='./time'>Current Time</a> -- streams text/plain; browsers buffer this.
<br>Try: <code>curl -s ($base)/time</code></li>
<li><a href='./info'>Request Info</a></li>
</ul>
</body></html>"
}
# Hello world example
"/hello" => {
"Hello, World!"
}
# JSON response example
"/json" => {
{
message: "This is JSON"
timestamp: (date now | into int)
server: "http-nu"
}
}
# Echo POST data
"/echo" => {
if $req.method == "POST" {
# Return the request body
$in
} else {
"<html><body>
<h1>Echo Service</h1>
<p>Send a POST request to this URL to echo the body.</p>
<form method='post'>
<textarea name='data'></textarea>
<br>
<button type='submit'>Submit</button>
</form>
</body></html>"
}
}
# Time stream example
"/time" => {
let _ = $in
generate {|_|
sleep 1sec
{out: $"Current time: (date now | format date '%Y-%m-%d %H:%M:%S')\n" next: true}
} true | metadata set --content-type "text/plain"
}
# Show request info
"/info" => {
$req
}
# 404 for everything else
_ => {
"404 - Page not found" | metadata set --merge {'http.response': {status: 404}}
}
}
}