1 # A simple HTTP library built using CURL
6 struct HTTPResponse(code:Int, body:Text)
8 enum _Method(GET, POST, PUT, PATCH, DELETE)
10 func _send(method:_Method, url:Text, data:Text?, headers:[Text]=[] -> HTTPResponse)
12 save_chunk := func(chunk:CString, size:Int64, n:Int64)
13 chunks.insert(C_code:Text`Text$from_strn(@chunk, @size*@n)`)
17 CURL *curl = curl_easy_init();
18 struct curl_slist *chunk = NULL;
19 curl_easy_setopt(curl, CURLOPT_URL, @(CString(url)));
20 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, @save_chunk.fn);
21 curl_easy_setopt(curl, CURLOPT_WRITEDATA, @save_chunk.userdata);
27 curl_slist_free_all(chunk);
28 curl_easy_cleanup(curl);
33 curl_easy_setopt(curl, CURLOPT_POST, 1L);
37 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, @(CString(posting)));
41 curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT");
45 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, @(CString(putting)));
49 curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PATCH");
53 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, @(CString(patching)));
57 curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE");
64 chunk = curl_slist_append(chunk, @(CString(header)));
69 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
74 CURLcode res = curl_easy_perform(curl);
76 fprintf(stderr, "curl_easy_perform() failed: %s\\n", curl_easy_strerror(res));
78 curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &@code);
80 return HTTPResponse(Int(code), "".join(chunks))
82 func get(url:Text, headers:[Text]=[] -> HTTPResponse)
83 return _send(GET, url, none, headers)
85 func post(url:Text, data="", headers=["Content-Type: application/json", "Accept: application/json"] -> HTTPResponse)
86 return _send(POST, url, data, headers)
88 func put(url:Text, data="", headers=["Content-Type: application/json", "Accept: application/json"] -> HTTPResponse)
89 return _send(PUT, url, data, headers)
91 func patch(url:Text, data="", headers=["Content-Type: application/json", "Accept: application/json"] -> HTTPResponse)
92 return _send(PATCH, url, data, headers)
94 func delete(url:Text, data:Text?=none, headers=["Content-Type: application/json", "Accept: application/json"] -> HTTPResponse)
95 return _send(DELETE, url, data, headers)
99 say(get("https://httpbin.org/get").body)
100 say("Waiting 1sec...")
103 say(post("https://httpbin.org/post", `{"key": "value"}`).body)
104 say("Waiting 1sec...")
107 say(put("https://httpbin.org/put", `{"key": "value"}`).body)
108 say("Waiting 1sec...")
111 say(delete("https://httpbin.org/delete").body)