-
Notifications
You must be signed in to change notification settings - Fork 6
/
http_lib.janet
100 lines (71 loc) · 2.16 KB
/
http_lib.janet
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
99
# http_lib.janet
(defn merged-table [arr]
(var output @{})
(let [parts (partition 2 arr)]
(each [k v] parts
(if (get output k)
(put output k (array/concat @[(get output k)] @[v]))
(put output k v))))
output)
(defn parse-headers [response]
(let [str (get response :headers "")]
(->> (string/split "\r\n" str)
(filter |(string/find ":" $))
(mapcat |(string/split ":" $ 0 2))
(map string/trim)
(merged-table)
(freeze))))
(defn prep-headers [headers]
(when headers
(map |(string/format "%s: %s" (first $) (last $)) (pairs headers))))
(defn request [method url options]
(let [options (merge options {:method method})
options (update options :headers prep-headers)
response (send-request url options)
headers (parse-headers response)]
(if-let [error-msg (response :error)]
(errorf "%s" error-msg))
(merge response {:headers headers})))
(defn form-encode [dict]
(if (not (dictionary? dict))
""
(do
(var output @"")
(var i 0)
(def len (length dict))
(eachp [k v] dict
(buffer/push-string output (string k "=" v))
(when (< (++ i) len)
(buffer/push-string output "&")))
(string output))))
(defn get
"Sends a get request with libcurl"
[url & options]
(request "GET" url (table ;options)))
(defn head
"Sends a head request with libcurl"
[url & options]
(request "HEAD" url (table ;options)))
(defn trace
"Sends a trace request with libcurl"
[url & options]
(request "TRACE" url (table ;options)))
(defn post
"Sends a post request with libcurl"
[url body & options]
(request "POST" url (merge (table ;options)
{:body body})))
(defn put
"Sends a put request with libcurl"
[url body & options]
(request "PUT" url (merge (table ;options)
{:body body})))
(defn patch
"Sends a patch request with libcurl"
[url body & options]
(request "PATCH" url (merge (table ;options)
{:body body})))
(defn delete
"Sends a delete request with libcurl"
[url & options]
(request "DELETE" url (table ;options)))