在Scotty中编译时动态添加路由

时间:2015-05-16 15:59:08

标签: haskell template-haskell scotty

是否可以通过使用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

1 个答案:

答案 0 :(得分: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)