我想做的是创建一个有点智能的反向代理服务器,它应该自己处理一些请求并将其他请求转发到选择的后端。为了使它具有挑战性,我正在努力在 Haskell 中做到这一点,我完全是新手。
这是我到目前为止提出的代码:
{-# LANGUAGE OverloadedStrings #-}
import Control.Applicative
import Data.ByteString
import Network.HTTP.ReverseProxy
import Network.HTTP.Types
import Network.Wai
import Network.Wai.Handler.Warp
import Network.Wai.Middleware.RequestLogger
import qualified Network.HTTP.Client as HC
helloApp :: Application
helloApp req respond =
respond $ responseLBS status200 [("Content-Type", "text/plain")] "Hello"
proxyStubApp :: Application
proxyStubApp req respond =
respond $ responseLBS status200 [("Content-Type", "text/plain")] "You've hit the stub"
proxyApp :: IO Application
proxyApp = do
manager <- HC.newManager HC.defaultManagerSettings
return $ waiProxyTo (const $ return $ WPRProxyDest ProxyDest { pdHost = "localhost", pdPort = 9393 }) defaultOnExc manager
app :: Application
app req respond =
serve req respond
where serve = lookupServeFunction req
lookupServeFunction :: Request -> Application
lookupServeFunction req
| isInfixOf "sample_path" (rawPathInfo req) = proxyStubApp
| otherwise = helloApp
main = run 3011 =<< (logStdoutDev <$> return app)
它工作得很好,但是当我换成proxyStubApp
实际的时,proxyApp
我不得不到处添加IO
。特别是它被添加到app
,因此给我留下以下编译错误消息:
Couldn't match expected type ‘Request -> t5 -> t4’
with actual type ‘IO Application’
The equation(s) for ‘app’ have two arguments,
but its type ‘IO Application’ has none
我觉得我理解它为什么会发生,但我不知道如何应对它:(或者我做错了什么?
谢谢!
PS 如果您想自己编译,这里是依赖项:wai warp http-types text bytestring wai-extra time http-reverse-proxy http-client