使用 WAI 中间件和 Scotty 提供静态 css 文件

Serve static css file using WAI middleware and Scotty

我有以下Main.hs

{-# LANGUAGE OverloadedStrings #-}

module Main where

import Web.Scotty
import Network.Wai.Middleware.RequestLogger
import Network.Wai.Middleware.Static
import Text.Blaze.Html.Renderer.Text (renderHtml)
import qualified Text.Blaze.Html5 as H
import Text.Blaze.Html5.Attributes
import Control.Monad.IO.Class

main :: IO ()
main = do
  scotty 3000 $ do
    middleware logStdoutDev
    middleware $ staticPolicy (noDots >-> addBase "static")
    get "/" $ do
        html $ renderHtml $
            H.docTypeHtml $
                H.html $ do
                    H.head $
                        H.link H.! rel "stylesheet" H.! href "stylesheet.css"
                    H.body $ do
                        H.h1 "Link Shortener"
                        H.form H.! method "POST" H.! action "/shorten" $ do
                            H.input H.! type_ "text" H.! name "url"
                            H.input H.! type_ "submit" H.! value "Shorten!"
    post "/shorten" $ do
        url <- param "url"
        liftIO $ putStrLn url
        redirect "/"

和以下目录结构(这是在 stack 项目中):

据我所知,对 /stylesheet.css 的 GET 请求应该服务于样式表,但我得到了 404。对 /static/stylesheet.css 的请求也是 404。是否有我的中间件策略或目录结构有问题吗?

这可能是“当前目录”问题。当从 Stack 项目目录中 运行 时,通常应将可执行文件启动,并将其当前目录设置为项目目录的根目录,而不是 app 子目录。如果将 static 目录上移一级,可能会修复它。

我能够让您的代码在 stack new ... simple 项目中正常工作,其中 static 项目根目录的子文件夹。

scottystatic/
|
|   stack.yaml, scottystatic.cabal, etc.
|
+-- src/
|       Main.hs
|
`-- static/
        stylesheet.css