[Haskell]仿django基于正则的url dispatching实现

在haskell CGI(fastcgi)程序中,对url 进行解析,通过正则表达式匹配,确定处理函数,并提取传递参数。

一个地址与处理函数对应表:

mapsList = [("^index$",            pageIndex),
                   ("^user/([a-zA-Z]+)$", pageHello)]

将列表转换成 HashTable 类型数据

urls <- liftIO $ HT.fromList HT.hashString  mapsList

CGI 主函数:在模式列表中寻找匹配的项,得到后匹配url获得参数

cgiMain env mapping= do
  setHeader "Content-type" "text/html"

  -- | Session process
  sessionId <- getOrNewSessionId
  
  -- | url disptching
  uri <- queryURI
  let uriPath = procUri $ uriQuery uri
  let reKeys = [fst i | i <- mapsList]

  case find (\re -> findit (pack re) (pack uriPath)) reKeys of
    Nothing -> do
       output "not found"
    Just re' -> do
      let ss = maybe [] tail (match (compile (pack re') []) (pack uriPath) []) 
      act <- liftIO $ HT.lookup mapping re'
      case act of
        Nothing -> output "no"
        Just act -> do
                 (s, redir) <- act env sessionId ss
                 case redir of
                   "" -> output $ showHtml s
                   addr -> redirect addr