This repository has been archived by the owner on Apr 12, 2018. It is now read-only.
/
#utils.clj#
68 lines (57 loc) · 2.05 KB
/
#utils.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
62
63
64
65
66
67
;; Copyright (c) Zachary Tellman. All rights reserved.
;; The use and distribution terms for this software are covered by the
;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
;; which can be found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(ns aloha.utils
(:require
[clojure.string :as str]
[clojure.tools.logging :as log])
(:import
[org.jboss.netty.handler.codec.http
HttpMessage
HttpMethod
HttpRequest
HttpChunk
HttpHeaders
HttpRequestDecoder
HttpResponseEncoder
HttpContentCompressor]
[org.jboss.netty.channel
Channel]
[java.net
InetAddress
InetSocketAddress]))
(def request-methods [:get :post :put :delete :trace :connect :head :options :patch])
(def netty-method->keyword
(zipmap
(map #(HttpMethod/valueOf (name %)) request-methods)
request-methods))
(defn request-method [^HttpRequest request]
(netty-method->keyword (.getMethod request)))
(defn http-headers [^HttpMessage msg]
(let [k (keys (.getHeaders msg))]
(zipmap
(map str/lower-case k)
(map #(.getHeader msg %) k))))
(defn http-content-type [^HttpMessage msg]
(.getHeader msg "Content-Type"))
(defn http-character-encoding [^HttpMessage msg]
(when-let [content-type (.getHeader msg "Content-Type")]
(->> (str/split content-type #"[;=]")
(map str/trim)
(drop-while #(not= % "charset"))
second)))
(defn http-content-length [^HttpMessage msg]
(when-let [content-length (.getHeader msg "Content-Length")]
(try
(Integer/parseInt content-length)
(catch Exception e
(log/error e (str "Error parsing content-length: " content-length))
nil))))
(defn request-uri [^HttpRequest request]
(first (str/split (.getUri request) #"[?]")))
(defn request-query-string [^HttpRequest request]
(second (str/split (.getUri request) #"[?]")))