Servant中的Html页面 - 如何组合REST API和静态html页面?

时间:2016-04-02 11:51:11

标签: haskell servant

我有一个简单的hello world Servant应用程序。我需要添加一些静态或动态的html页面。我怎样才能做到这一点?在文档中没有提到。注意我不想在Haskell代码中创建html布局,我希望Haskell显示已经创建的html页面。

更新:

我该如何结合这个:

type MyApi = "/" :> Raw

server :: Server MyApi
server = serveDirectory "static/" -- index.html, about.html 

我已经拥有的东西:

  type API = 
    "api" :> "items" :> Get '[JSON] [MyData] :<|>
    "api" :> "items" :> Capture "id" Int :> Get '[JSON] MyData


  app :: Application
  app = serve api server

  api :: Proxy API
  api = Proxy

  server :: Server API
  server = getItems :<|> getItem

  startApp :: IO ()
  startApp =  run 1234 app

UPDATE2:

工作:

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

不工作,根本没有回应:

type API = 
    "api" :> "items" :> Get '[JSON] [MyData] :<|>
    "api" :> "items" :> Capture "id" Int :> Get '[JSON] MyData :<|>
    "/" :> Raw

-- or

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

我想知道为什么?

1 个答案:

答案 0 :(得分:4)

  

如何组合REST API和静态html页面?

您可以通过serveDirectory在根路径上提供包含静态网站的目录。它必须是您的Servant API中的最后一种情况,否则永远不会匹配其他情况。

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

api :: Proxy API 
api = Proxy

server :: Server API 
server = getItems
    :<|> getItem 
    :<|> serveDirectory "static/"

如果任何静态页面名称与您的API崩溃,它将被遮蔽。

  

为什么不是"/" :> Raw

看起来我的浏览器缓存了一些静态页面。清除缓存后,"/" :> Raw/index.html下没有回复。

api中的字符串文字将首先编码为合法的uri部分,因此"/"将为"%2F",您的文件将映射到/%2F/index.html,依此类推。

  

你知道如何处理根案例吗?

要在根路径上提供响应,您可以定义一个没有前缀的Get端点:

type API = Get '[HTML] RawHtml

除最后一行外,它可以在您的API中的任何位置。

要将本地文件作为html响应提供,您必须将该文件与其他字节串区分开来,或者将其包装为newtype:

newtype RawHtml = RawHtml { unRaw :: BS.ByteString }

-- tell Servant how to render the newtype to html page, in this case simply unwrap it
instance MimeRender HTML RawHtml where
    mimeRender _ =  unRaw

并在您的控制器中:

-- ...
:<|> fmap RawHtml (liftIO $ BS.readFile "your/file/path.html")

或者如果页面已经有另一个地址,您可以在那里重定向用户:

-- ...
:<|> throwError err301 { errHeaders = [("Location", "index.html")] }
  

它已经返回index.html。嗯,为什么究竟是index.html?

serveDirectory使用设置staticApp调用wai应用defaultFileServerSettings。在该设置中,如果出现问题,用户将被重定向到index.htmindex.html

defaultFileServerSettings root = StaticSettings
    { ssLookupFile = fileSystemLookup (fmap Just . hashFile) root
    , ssMkRedirect = defaultMkRedirect
    , ssGetMimeType = return . defaultMimeLookup . fromPiece . fileName
    , ssMaxAge = NoMaxAge
    , ssListing = Just defaultListing
    , ssIndices = map unsafeToPiece ["index.html", "index.htm"]
    , ssRedirectToIndex = False
    , ssUseHash = False
    , ssAddTrailingSlash = False
    , ss404Handler = Nothing
    }
相关问题