diff --git a/http.c b/http.c index 8578134..0330035 100644 --- a/http.c +++ b/http.c @@ -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); @@ -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); @@ -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); diff --git a/http_lib.janet b/http_lib.janet index d50c8b4..383b228 100644 --- a/http_lib.janet +++ b/http_lib.janet @@ -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}))) diff --git a/test/http-test.janet b/test/http-test.janet index 5c6b8c3..37126de 100644 --- a/test/http-test.janet +++ b/test/http-test.janet @@ -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")