-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path04_request_response.ring
More file actions
98 lines (79 loc) · 2.3 KB
/
04_request_response.ring
File metadata and controls
98 lines (79 loc) · 2.3 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# Request & Response - Headers, Status Codes, Body
# Run: ring 04_request_response.ring
load "bolt.ring"
new Bolt() {
// Reading request headers
// curl http://localhost:3000/headers -H "X-Custom-Header: MyValue" -H "User-Agent: TestClient"
@get("/headers", func {
cUserAgent = $bolt.header("User-Agent")
cCustom = $bolt.header("X-Custom-Header")
$bolt.json([
:userAgent = cUserAgent,
:custom = cCustom,
:requestId = $bolt.requestId()
])
})
// Setting response headers
// curl -i http://localhost:3000/custom-headers
@get("/custom-headers", func {
$bolt.setHeader("X-Powered-By", "Bolt")
$bolt.setHeader("X-Version", "1.0")
$bolt.setHeader("X-Request-Time", "" + $bolt.unixtime())
$bolt.send("Check the response headers!")
})
// Status codes
// curl -i http://localhost:3000/status/404
@get("/status/:code", func {
cCode = $bolt.param("code")
nCode = 0 + cCode
$bolt.jsonWithStatus(nCode, [
:statusCode = nCode,
:message = "Status code set"
])
})
// Reading request body
// curl -X POST http://localhost:3000/echo -d "Hello, Bolt!"
@post("/echo", func {
cBody = $bolt.body()
$bolt.setHeader("Content-Type", "text/plain")
$bolt.send("You sent: " + cBody)
})
// JSON request body
// curl -X POST http://localhost:3000/json -H "Content-Type: application/json" -d '{"name":"Bolt","version":1}'
@post("/json", func {
cBody = $bolt.body()
? "Received JSON: " + cBody
$bolt.json([
:received = cBody,
:processed = true
])
})
// Redirect
// curl -L http://localhost:3000/old-url
@get("/old-url", func {
$bolt.redirect("/new-url")
})
@get("/new-url", func {
$bolt.send("You were redirected here!")
})
@get("/", func {
$bolt.html(`<h1>Request & Response Example</h1>
<h3>Test these endpoints:</h3>
<pre>
// Headers
curl http://localhost:3000/headers -H 'X-Custom-Header: MyValue'
// Custom response headers
curl -i http://localhost:3000/custom-headers
// Status codes
curl -i http://localhost:3000/status/200
curl -i http://localhost:3000/status/404
curl -i http://localhost:3000/status/500
// Redirect
curl -L http://localhost:3000/old-url
// POST echo
curl -X POST http://localhost:3000/echo -d "Hello, Bolt!"
// POST JSON
curl -X POST http://localhost:3000/json -H "Content-Type: application/json" -d '{"name":"Bolt"}'
</pre>`)
})
}