捕获所有或默认路由

时间:2016-11-17 09:54:03

标签: haskell servant

现在,如果请求的路由与现有的API端点或其他静态资产不匹配,则需要从后端返回文件(例如index.html)并不罕见。使用react-routerbrowserHistory时,这非常方便。

我对于如何与Servant接触这一点感到有点难过。我确实想知道拦截404是否可能是要走的路,但当然有时API需要合法地发出404.这就是我用来试验的那种东西:

data Wombat = Wombat
  { id :: Int
  , name :: String
  } deriving (Eq, Show, Generic)
instance ToJSON Wombat

wombatStore :: [Wombat]
wombatStore = 
  [ Wombat 0 "Gertrude"
  , Wombat 1 "Horace"
  , Wombat 2 "Maisie"
  , Wombat 3 "Julius"
  ]

wombats :: Handler [Wombat]
wombats = return wombatStore

wombat :: Int -> Handler Wombat
wombat wid = do
  case find (\w -> Main.id w == wid) wombatStore of
    Just x -> return x
    Nothing -> throwE err404

type API = 
    "api" :> "wombats" :> Get '[JSON] [Wombat] :<|>
    "api" :> "wombats" :> Capture "id" Int :> Get '[JSON] Wombat :<|>
    Raw

api :: Proxy API
api = Proxy

server :: Server API 
server = wombats
  :<|> wombat
  :<|> serveDirectory "static"

app :: Application
app = serve api server

main :: IO ()
main = run 3000 app

如果请求与API端点或静态目录中的任何内容不匹配,我希望看到如何添加发送HTML响应的“默认路由”的示例。玩具回购here

2 个答案:

答案 0 :(得分:2)

基本上,你得到了它。 serveDirectory "static"可以被任何wai Application取代,例如,我们可以拥有:

...
{-# LANGUAGE OverloadedStrings #-}
...
import Network.Wai        (responseLBS)
import Network.HTTP.Types (status200)
...
server :: Server API 
server = wombats
    :<|> wombat
    :<|> hello

hello :: Application
hello req respond = respond $ 
  responseLBS 
  status200                        -- 
  [("Content-Type", "text/plain")] -- headers
  "Hello, World!"                  -- content
...

首先,wai应用程序只是Request -> Response,但the docs告诉更全面的故事:

Request -> (Response -> IO ResponseReceived) -> IO ResponseReceived

因此,由于您可以访问IO,因此您可以检查文件是否存在,如果存在,请执行此操作,否则请执行任何操作。事实上,wai定义了type Middleware = Application -> Application,所以你可能想出一个方便的中间件,它将hello(或任何其他应用程序!)包装在文件存在 - 检查器和服务器中。

答案 1 :(得分:2)

这是另一条路线:

serveDirectory定义为

serveDirectory = staticApp . defaultFileServerSettings . addTrailingPathSeparator

defaultFileServerSettings包含一个字段ssLookupFile,如果找不到该文件,您可以更改该字段以提供所需内容。也许:

import WaiAppStatic.Types
import WaiAppStatic.Storage.Filesystem
import Network.Wai.Application.Static
import System.FilePath

fileOrIndex root pieces = do
  res <- ssLookupFile (defaultFileServerSettings root) pieces
  case res of
    LRNotFound -> undefined -- index.html here
    _ -> return res

serveStatic root =
  let root' = addTrailingPathSeparator root in
  staticApp $ (defaultFileServerSettings root') {ssLookupFile = fileOrIndex root'}