Debian Codegraph @

Network/Wai/Application/Classic/Field.hs

raw
1 {-# LANGUAGE OverloadedStrings #-}
2
3 module Network.Wai.Application.Classic.Field where
4
5 import Control.Arrow (first)
6 import Control.Monad (mplus)
7 import Data.ByteString (ByteString)
8 import qualified Data.ByteString as BS
9 import qualified Data.ByteString.Char8 as B8
10 import qualified Data.Map as Map
11 import Data.Maybe
12 import Data.StaticHash (StaticHash)
13 import qualified Data.StaticHash as SH
14 import qualified Data.Text as T
15 import Network.HTTP.Types
16 import Network.Mime (defaultMimeMap, defaultMimeType, MimeType)
17 import Network.SockAddr
18 import Network.Wai
19 import Network.Wai.Application.Classic.Header
20 import Network.Wai.Application.Classic.Lang
21 import Network.Wai.Application.Classic.Types
22
23 ----------------------------------------------------------------
24
25 languages :: RequestHeaders -> [ByteString]
26 languages = maybe [] parseLang . lookup hAcceptLanguage
27
28 ----------------------------------------------------------------
29
30 textPlainHeader :: ResponseHeaders
31 textPlainHeader = [(hContentType,"text/plain")]
32
33 textHtmlHeader :: ResponseHeaders
34 textHtmlHeader = [(hContentType,"text/html")]
35
36 locationHeader :: ByteString -> ResponseHeaders
37 locationHeader url = [(hLocation, url)]
38
39 -- FIXME: the case where "Via:" already exists
40 addVia :: ClassicAppSpec -> Request -> ResponseHeaders -> ResponseHeaders
41 addVia cspec req hdr = (hVia, val) : hdr
42 where
43 ver = httpVersion req
44 val = BS.concat [
45 showBS (httpMajor ver)
46 , "."
47 , showBS (httpMinor ver)
48 , " "
49 , host
50 , " ("
51 , softwareName cspec
52 , ")"
53 ]
54 host = fromMaybe "" $ requestHeaderHost req
55
56 addForwardedFor :: Request -> ResponseHeaders -> ResponseHeaders
57 addForwardedFor req hdr = (hXForwardedFor, addr) : hdr
58 where
59 addr = B8.pack . showSockAddr . remoteHost $ req
60
61 newHeader :: Bool -> ByteString -> ResponseHeaders
62 newHeader ishtml file
63 | ishtml = textHtmlHeader
64 | otherwise = [(hContentType, mimeType file)]
65
66 mimeType :: ByteString -> MimeType
67 mimeType file = fromMaybe defaultMimeType . foldr mplus Nothing . map lok $ targets
68 where
69 targets = extensions file
70 lok x = SH.lookup x defaultMimeTypes'
71
72 extensions :: ByteString -> [ByteString]
73 extensions file = exts
74 where
75 entire = case BS.break (== 46) file of -- '.'
76 (_,"") -> ""
77 (_,x) -> BS.tail x
78 exts = if entire == "" then [] else entire : BS.split 46 file
79
80 defaultMimeTypes' :: StaticHash ByteString MimeType
81 defaultMimeTypes' = SH.fromList $ map (first (B8.pack . T.unpack)) $ Map.toList defaultMimeMap
82
83 showBS :: Show a => a -> ByteString
84 showBS = B8.pack . show