在haskell HTTP服务器中实现路由

在haskell HTTP服务器中实现路由

问题描述:

我试图建立一个简单的方式来路由基于主机名的请求。下面是函数:在haskell HTTP服务器中实现路由

handleAccept :: Handle -> String -> IO() 
handleAccept handle hostname = do 
    putStrLn $ "Handling request from " ++ (getMessage hostname) 
    request <- fmap (parseRequest . lines) (hGetContents handle) 
    respond request handle 
    return() 
    where getMessage x 
     | x == "hello" = "hello route" 
     | x == "LOL" = "what's so funny?" 
     | otherwise = x 

这里所说的:

main = withSocketsDo $ do 
    sock <- listenOn (PortNumber 9000) 
    putStrLn "Listening on port 9000" 
    forever $ do 
     (handle, hostname, port) <- accept sock 
     handleAccept handle hostname 
     hClose handle 

当我尝试编译我得到这个错误:

parse error (possibly incorrect indentation or mismatched brackets) 

在这一行handleAccept

where getMessage x 
     | x == "hello" = "hello route" 

看起来好像这是一个使用警卫和where语句的问题。所以我尝试了这个虚拟功能:

wherePlusGuards :: String -> Bool 
wherePlusGuards x = getX x 
    where getX x 
     | x == "hello" = True 
     | otherwise = False 

这个编译好。我仍然相信这个问题来自于使用where语句和里面的 a do表达式。为什么会这样?请帮帮我。

确保|是比ggetMessage进一步缩进 - 比如:

import System.IO 

handleAccept :: Handle -> String -> IO() 
handleAccept handle hostname = do 
    putStrLn $ "Handling request from " ++ (getMessage hostname) 
    return() 
    where getMessage x 
      | x == "hello" = "hello route" 
      | x == "LOL" = "what's so funny?" 
      | otherwise = x 

更新

这并不正确解析:

wherePlusGuards :: String -> Bool 
wherePlusGuards x = getX x 
    where getX x 
     | x == "hello" = True 
     | otherwise = False 

它产生的错误:parse error (possibly incorrect indentation or mismatched brackets)

注意:我没有使用任何选项卡。

从Haskell2010报告:

Note 1. A nested context must be further indented than the enclosing context (n > m). If not, L fails, and the compiler should indicate a layout error.

参考:https://www.haskell.org/onlinereport/haskell2010/haskellch10.html

10.3节(布局),注1.

+0

为什么会是怎么回事?解析器查找的缩进计数是多少? – dopatraman

+0

答案更新 - 你确定'哪里的PlusGuard解析好吗?它不会为我解析。 – ErikR

+0

添加了Haskell报告的参考。 – ErikR