Skip to content

Commit c6fd4c0

Browse files
committed
Fix request-rewrite-proxy example
And add it to the cabal file.
1 parent ecfe5de commit c6fd4c0

File tree

2 files changed

+43
-10
lines changed

2 files changed

+43
-10
lines changed

Diff for: example/request-rewrite-proxy.hs

+31-10
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,48 @@
11
{-# LANGUAGE OverloadedStrings #-}
22

3-
import Network.HTTP.Proxy (ProxySettings (..), Request (..))
3+
import qualified Data.ByteString.Char8 as BS
4+
5+
import Network.HTTP.Proxy (Settings (..), Request (..))
46
import qualified Network.HTTP.Proxy as Proxy
7+
import Network.URI (URI (..), URIAuth (..), parseURI)
8+
import Network.Wai.Internal (Response)
59

610
main :: IO ()
711
main =
812
Proxy.runProxySettings $
913
Proxy.defaultProxySettings
1014
{ proxyPort = 31081
11-
, proxyHttpRequestModifier = Just secureGoogle
15+
, proxyHttpRequestModifier = secureGoogle
1216
}
1317

1418
-- Modifying the request like this is only possible for unencrypted HTTP connections
1519
-- by my be useful for eg redirecting HTTP to HTTPS.
1620
-- HTTPS cnnections cannot be modified like this because the for HTTPS connections
1721
-- even the request itself is encrypted.
1822

19-
secureGoogle :: Request -> IO Request
20-
secureGoogle req
21-
| "www.google.com" `BS.isInfixOf` requestPath req
22-
&& not ("https" `BS.isprefixOf` requestPath req =
23-
pure $ req
24-
{ requestPath = "encrypted.google.com"
25-
}
23+
secureGoogle :: Request -> IO (Either Response Request)
24+
secureGoogle req = do
25+
case parseURI $ BS.unpack (requestPath req) of
26+
Nothing -> do
27+
putStrLn $ "Not able to parse: " ++ show (requestPath req)
28+
-- Not much to be done other than just return the Request unmodified.
29+
pure $ Right req
30+
Just uri ->
31+
pure . Right $ req { requestPath = BS.pack $ show (modifyURI uri) }
32+
33+
modifyURI :: URI -> URI
34+
modifyURI uri =
35+
uri
36+
{ uriAuthority = modifyUriAthority <$> uriAuthority uri
37+
, uriScheme = modifyUriScheme (uriScheme uri)
38+
}
39+
where
40+
modifyUriAthority :: URIAuth -> URIAuth
41+
modifyUriAthority auth =
42+
if uriRegName auth == "www.google.com"
43+
then auth { uriRegName = "encrypted.google.com", uriPort = "" }
44+
else auth
2645

27-
| otherwise = pure req
46+
modifyUriScheme :: String -> String
47+
modifyUriScheme scheme =
48+
if scheme =="http:" then "https:" else scheme

Diff for: http-proxy.cabal

+12
Original file line numberDiff line numberDiff line change
@@ -154,3 +154,15 @@ executable simple-proxy
154154

155155
build-depends: base
156156
, http-proxy
157+
158+
executable request-rewrite-proxy
159+
default-language: Haskell2010
160+
ghc-options: -Wall -fwarn-tabs -threaded -rtsopts "-with-rtsopts=-H1m -K1m"
161+
hs-source-dirs: example
162+
main-is: request-rewrite-proxy.hs
163+
164+
build-depends: base
165+
, bytestring
166+
, http-proxy
167+
, network-uri
168+
, wai

0 commit comments

Comments
 (0)