如何在Scotty中使用静态中间件设置标头?

时间:2019-03-19 11:39:52

标签: haskell scotty

假设我有一份静态文件,但是没有扩展名。我想为所有来自“ some /” (第一条规则)的设置标题“ Content-Type:image / png”。在此代码中如何执行?

import Network.Wai.Middleware.Static
import Web.Scotty

routes :: Scotty M ()
routes = do
  ...
  middleware $ staticPolicy $
    contains "some/" >-> (addBase "/something/files/")
    <|>
    addBase "/elsewhere/"

我尝试过:

setContentType :: Middleware
setContentType = modifyResponse $ mapResponseHeaders 
(("Content-Type", "image/png"):)

reqInfixedWith :: Text -> Request -> Bool
reqInfixedWith str req =
  isInfixOf str $ convertString $ rawQueryString req

...

-- in routes
  middleware $ ifRequest (reqInfixedWith "some/") setContentType

并使用Debug.Trace请求的路径进行检查,查询字符串-全部为空,而实际请求为“ ...:8080 / some / somefile”。

正确的方法是什么?

1 个答案:

答案 0 :(得分:1)

您需要Web.Scotty的addHeader函数:

http://hackage.haskell.org/package/scotty-0.11.3/docs/Web-Scotty.html

addHeader :: Text -> Text -> ActionM ()

示例:

{-#Language OverloadedStrings#-}
import           Network.Wai.Middleware.Static
import           Web.Scotty

main :: IO ()
main = do
  scotty 3000 $ do
    middleware static
    get "/some/:file" $ do
      f <- param "file"
      addHeader "Content-Type" "image/png"
      file f

http://localhost:3000/some/image的请求将产生一个名为“ image”的文件,其内容类型为image/png

enter image description here