-
Notifications
You must be signed in to change notification settings - Fork 20
/
core.clj
61 lines (55 loc) · 2.32 KB
/
core.clj
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
(ns peridot.core
(:require [clojure.data.codec.base64 :as base64]
[peridot.cookie-jar :as pcj]
[peridot.request :as pr]
[ring.util.response :as rur]))
(defn session
"Creates an initial state for passing through the api."
[app & params]
(assoc (apply hash-map params) :app app))
(defn request
"Send a request to the ring app, returns state containing :response and :request sent to and returned from the ring app."
[{:keys [app headers cookie-jar content-type]} uri & env]
(let [env (apply hash-map env)
request-content-type (or (:content-type env) content-type)
request (pr/build uri env headers cookie-jar request-content-type)
response (app request)]
(session app
:response response
:request request
:headers headers
:content-type content-type
:cookie-jar (pcj/merge-cookies (:headers response)
cookie-jar
(:uri request)
(pr/get-host request)))))
(defn header
"Set headers to be sent for future requests."
[state key value]
(assoc-in state [:headers key] value))
(defn content-type
"Set content-type to be sent for future requests."
[state value]
(assoc state :content-type value))
(defn authorize
"Set basic authorization to be used in future requests."
[state user pass]
(header state "authorization" (str "Basic "
(String. ^"[B" (base64/encode
(.getBytes (str user ":" pass)
"UTF-8"))
"UTF-8"))))
(defn- expand-location
"Expand a location header into an absolute url"
[location request]
(if (re-find #"://" location)
location
(pr/url (assoc request :uri location :query-string nil))))
(defn follow-redirect
"Follow the redirect from the previous response."
[state]
(if-let [location (rur/get-header (:response state) "Location")]
(request state
(expand-location location (:request state))
:headers {"referer" (pr/url (:request state))})
(throw (IllegalArgumentException. "Previous response was not a redirect"))))