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
|
//// the module implements a few njs exmpales found at
//// https://github.com/nginx/njs-examples
////
import gleam/dynamic/decode
import gleam/javascript/array
import gleam/javascript/promise.{type Promise}
import gleam/json
import gleam/result
import gleam/string
import njs/http.{type HTTPRequest}
import njs/ngx
pub fn version(r: HTTPRequest) -> Nil {
r
|> http.return_text(200, ngx.version())
}
pub fn hello(r: HTTPRequest) -> Nil {
let l =
[True, False, False]
|> ngx.make_array
|> array.map(fn(x) {
case x {
True -> "1"
False -> "0"
}
})
|> array.to_list
|> string.concat
r
|> http.return_text(200, l)
}
pub fn decode_uri(r: HTTPRequest) -> String {
let decoder = {
use value <- decode.field("foo", decode.string)
decode.success(value)
}
r
|> http.args
|> json.parse(decoder)
|> result.unwrap("")
}
pub fn join(r: HTTPRequest) -> Promise(Nil) {
let fs =
["/foo", "/bar"]
|> ngx.make_array
|> array.map(http.subrequest(r, _, ""))
|> promise.await_array
use rs <- promise.await(fs)
rs
|> array.map(fn(re) {
ngx.object()
|> ngx.merge("uri", re |> http.uri)
|> ngx.merge("code", re |> http.status)
|> ngx.merge("body", re |> http.response_text)
// [
// #("uri", re |> http.uri |> json.string),
// #("code", re |> http.status |> json.int),
// #("body", re |> http.response_text |> json.string),
// ]
// |> json.object
})
|> ngx.to_json
|> fn(b) {
http.set_headers_out(r, "Content-Type", "application/json")
b
}
|> json.to_string
|> http.return_text(r, 200, _)
|> promise.resolve
}
|