0

是否可以使用 Template 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
4

1 回答 1

2

好的,鉴于上面的列表,我假设您正在寻找相当于手动编写以下内容的内容:

{-! LANGUAGE OverloadedStrings #-}
import Web.Scotty
import Data.String

main = scotty 3000 $ do
  middleware logStdoutDev
  get (fromString $ '/' : "hello") (text "hello")
  get (fromString $ '/' : "world") (text "world")

好消息是,那里没有任何东西需要任何 TH 魔法!

请记住,addroute/get只是返回ScottyM ()值的常规函数​​。如果我有

r1 = get (fromString $ '/' : "hello") (text "hello")
r2 = get (fromString $ '/' : "world") (text "world")

那么前面的main函数完全等价于

main = do
  middleware logStdoutDev
  r1
  r2

这以及常见的结构r1r2建议以下解决方案:

import Control.Monad (forM_)

main = do
  middleware logStdoutDev
  forM_ sampleRoutes $ \(name, response) -> 
    get (fromString $ '/':name) (text response)
于 2015-05-18T12:31:56.640 回答