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 '')"
$"
http-nu demo
Hello World
JSON Example
POST Echo
Current Time -- streams text/plain; browsers buffer this.
Try: curl -s ($base)/time
Request Info
"
}
# 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 {
"
Echo Service
Send a POST request to this URL to echo the body.
Submit
"
}
}
# 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}} }
}
}
}