Skip to content

Commit

Permalink
Send request headers
Browse files Browse the repository at this point in the history
  • Loading branch information
swlkr committed Feb 1, 2020
1 parent de13952 commit 7293164
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 1 deletion.
19 changes: 19 additions & 0 deletions http.c
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,15 @@ static Janet c_send_request(int32_t argc, Janet *argv) {
method = (char *)janet_unwrap_string(janet_method);
}

Janet janet_headers = janet_table_get(options, janet_ckeywordv("headers"));
JanetArray *request_headers = NULL;

if(janet_checktype(janet_headers, JANET_ARRAY)) {
request_headers = janet_unwrap_array(janet_headers);
}

JanetTable *response_table = NULL;
struct curl_slist *curl_slist = NULL;

if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, url);
Expand All @@ -113,6 +121,16 @@ static Janet c_send_request(int32_t argc, Janet *argv) {
// tcp keep alive
curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, keep_alive);

// request headers
if(request_headers != NULL) {
for(int32_t i = 0; i < request_headers->count; i++) {
Janet header_string = janet_array_pop(request_headers);
curl_slist = curl_slist_append(curl_slist, (char *)janet_unwrap_string(header_string));
}

curl_easy_setopt(curl, CURLOPT_HTTPHEADER, curl_slist);
}

// request body
if(request_body) {
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, request_body);
Expand Down Expand Up @@ -145,6 +163,7 @@ static Janet c_send_request(int32_t argc, Janet *argv) {

/* cleanup */
curl_easy_cleanup(curl);
curl_slist_free_all(curl_slist);
curl_global_cleanup();
free(body.memory);
free(headers.memory);
Expand Down
6 changes: 6 additions & 0 deletions http_lib.janet
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,14 @@
(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)]
(merge response {:headers headers})))
Expand Down
9 changes: 8 additions & 1 deletion test/http-test.janet
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
(import tester :prefix "" :exit true)
(import build/http :as http)


(deftest
(test "prep-headers"
(deep= @["accept: application/json"] (http/prep-headers {"accept" "application/json"})))

(test "request headers"
(string/find "text/plain"
(-> (http/get "https://postman-echo.com/get" :headers {"Accept" "text/plain"})
(get :body))))

(test "get"
(= 200
(-> (http/get "http://example.com")
Expand Down

0 comments on commit 7293164

Please sign in to comment.