-
Notifications
You must be signed in to change notification settings - Fork 135
/
Copy pathUtil.hs
61 lines (48 loc) · 1.93 KB
/
Util.hs
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
module Web.Scotty.Util
( lazyTextToStrictByteString
, strictByteStringToLazyText
, setContent
, setHeaderWith
, setStatus
, mkResponse
, replace
, add
, addIfNotPresent
) where
import Network.Wai
import Network.HTTP.Types
import qualified Data.ByteString as B
import qualified Data.Text.Lazy as T
import qualified Data.Text.Encoding as ES
import Web.Scotty.Internal.Types
lazyTextToStrictByteString :: T.Text -> B.ByteString
lazyTextToStrictByteString = ES.encodeUtf8 . T.toStrict
strictByteStringToLazyText :: B.ByteString -> T.Text
strictByteStringToLazyText = T.fromStrict . ES.decodeUtf8
setContent :: Content -> ScottyResponse -> ScottyResponse
setContent c sr = sr { srContent = c }
setHeaderWith :: ([(HeaderName, B.ByteString)] -> [(HeaderName, B.ByteString)]) -> ScottyResponse -> ScottyResponse
setHeaderWith f sr = sr { srHeaders = f (srHeaders sr) }
setStatus :: Status -> ScottyResponse -> ScottyResponse
setStatus s sr = sr { srStatus = s }
-- Note: we currently don't support responseRaw, which may be useful
-- for websockets. However, we always read the request body, which
-- is incompatible with responseRaw responses.
mkResponse :: ScottyResponse -> Response
mkResponse sr = case srContent sr of
ContentBuilder b -> responseBuilder s h b
ContentFile f -> responseFile s h f Nothing
ContentStream str -> responseStream s h str
where s = srStatus sr
h = srHeaders sr
-- Note: we assume headers are not sensitive to order here (RFC 2616 specifies they are not)
replace :: Eq a => a -> b -> [(a,b)] -> [(a,b)]
replace k v = add k v . filter ((/= k) . fst)
add :: Eq a => a -> b -> [(a,b)] -> [(a,b)]
add k v m = (k,v):m
addIfNotPresent :: Eq a => a -> b -> [(a,b)] -> [(a,b)]
addIfNotPresent k v = go
where go [] = [(k,v)]
go l@((x,y):r)
| x == k = l
| otherwise = (x,y) : go r