是否可以使用模板Haskell或任何其他方式在编译时通过配置文件动态添加路由。
Scotty有一个函数addRoute,但我想动态使用它。
示例
import qualified Data.Text.Lazy as LTB
sampleRoutes :: [(String, LTB.Text)]
sampleRoutes = [("hello", LTB.pack "hello"), ("world", LTB.pack "world")]我想在sampleRoutes数组上迭代,并在编译时定义路由和响应。
import Web.Scotty
main = scotty 3000 $ do
middleware logStdoutDev
someFunc sampleRoutes发布于 2015-05-18 12:31:56
好的,考虑到上面的列表,我假设您正在寻找的东西相当于手工编写以下内容:
{-! LANGUAGE OverloadedStrings #-}
import Web.Scotty
import Data.String
main = scotty 3000 $ do
middleware logStdoutDev
get (fromString $ '/' : "hello") (text "hello")
get (fromString $ '/' : "world") (text "world")好消息是,里面没有任何东西需要任何魔法!
请记住,addroute / get只是返回ScottyM ()值的常规函数。如果我有
r1 = get (fromString $ '/' : "hello") (text "hello")
r2 = get (fromString $ '/' : "world") (text "world")然后前面的main函数完全等价于
main = do
middleware logStdoutDev
r1
r2这一点以及r1和r2的共同结构提出了以下解决方案:
import Control.Monad (forM_)
main = do
middleware logStdoutDev
forM_ sampleRoutes $ \(name, response) ->
get (fromString $ '/':name) (text response)https://stackoverflow.com/questions/30277790
复制相似问题