aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/library/lux/world/net/http/response.lux
blob: 9c280d0197b4b9274bb253c1f1f9bffdf2a2fc1a (plain)
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
(.require
 [library
  [lux (.except)
   [control
    ["[0]" try]
    [concurrency
     ["[0]" async (.only Async)]]]
   [data
    ["[0]" binary (.only Binary)]
    [text
     [encoding
      ["[0]" utf8]]]
    [format
     ["[0]" html]
     ["[0]" css (.only CSS)]
     ["[0]" json (.only JSON) (.use "[1]#[0]" codec)]]]]]
 ["[0]" // (.only Body Message)
  ["[0]" status (.only Status)]
  ["[0]" header]
  [// (.only URL)
   ["[0]" mime (.only MIME)]]])

(type .public (Response !)
  (Record
   [#status Status
    #message (Message !)]))

(def .public empty
  (-> Status (Response Async))
  (let [body (is (Body Async)
                 (function (_ _)
                   (async.resolved {try.#Success [0 (at utf8.codec encoded "")]})))]
    (function (_ status)
      [#status status
       #message [//.#headers (|> header.empty
                                 (header.has header.content_length 0)
                                 (header.has header.content_type mime.utf_8))
                 //.#body body]])))

(def .public (temporary_redirect to)
  (-> URL (Response Async))
  (|> status.temporary_redirect
      ..empty
      (revised [#message //.#headers] (header.has header.location to))))

(def .public not_found
  (Response Async)
  (..empty status.not_found))

(def .public (content status type data)
  (-> Status MIME Binary (Response Async))
  (let [length (binary.size data)]
    [#status status
     #message [//.#headers (|> header.empty
                               (header.has header.content_length length)
                               (header.has header.content_type type))
               //.#body (function (_ _)
                          (async.resolved {try.#Success [length data]}))]]))

(def .public bad_request
  (-> Text (Response Async))
  (|>> (at utf8.codec encoded)
       (content status.bad_request mime.utf_8)))

(def .public ok
  (-> MIME Binary (Response Async))
  (content status.ok))

(with_template [<name> <type> <mime> <pre>]
  [(def .public <name>
     (-> <type> (Response Async))
     (|>> <pre>
          (at utf8.codec encoded)
          (..ok <mime>)))]

  [text Text          mime.utf_8 (<|)]
  [html html.Document mime.html  html.html]
  [css  (CSS Any)     mime.css   css.css]
  [json JSON          mime.json  json#encoded]
  )