Converting CURL header to Clojure map

less than 1 minute read

Code

;; curl_headers.clj

(use '[clojure.java.shell :only [sh]])
(require '[clojure.string :as str])

;; Got both below functions from 
;; https://stackoverflow.com/questions/31138653/clojure-idiomatic-way-to-write-split-first-and-split-last

(defn split-first [s re]
  (str/split s re 2))

(defn split-last [s re]
  (let [pattern (re-pattern (str re "(?!.*" re ")"))]
    (split-first s pattern)))

(defn string-to-map [s re]
  (let [[k v] (map #(str/trim %) (split-first s re))]
    {k v}))

(defn curl-header-to-map [s]
  (let [lines (str/split s #"\n")
        first_line (first lines)
        rest_of_lines (rest lines)
        [protocol status] (str/split first_line #"\s+")
        rest_of_lines_to_map (apply merge (map #(string-to-map % #":") rest_of_lines))]
    (merge {"protocol" protocol "status" status} rest_of_lines_to_map)))

;; curl -X HEAD -I https://something.com
;; (def curl-header (slurp "curl_output.txt"))

(defn curl-headers [url]
  (curl-header-to-map (:out (sh "curl" "-X" "HEAD" "-I" url))))

(curl-headers "https://something.com")

(get (curl-headers "https://something.com") "content-type")
(get (curl-headers "https://bafybeiglw52c2scnonhlemktgtmj4y3ufvsqg24bdf4fbqg7padhqpxz3q.ipfs.nftstorage.link/clohure_diary_round_logo.svg") "content-type")
(get (curl-headers "https://mindaslab.github.io/me.jpg") "content-type")

Updated: