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

How to set a header with static middleware in Scotty?

假设我有一份静态文件服务,但它们没有扩展名。我想为从 "some/" 服务的所有 设置 header "Content-Type: image/png"(第 1 条规则)。如何在这段代码中做到这一点?

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”。

正确的做法是什么?

您想要 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: