2016-08-24 39 views
0

我想寫的HTML頁面時一定路徑被擊中:如何將HTML寫入句柄?

import Control.Monad 
import Data.Char 
import System.IO 
import Network 
import Data.Time.LocalTime 

data RequestType = GET | POST deriving (Show) 
data Request = Request { rtype :: RequestType, path :: String, options :: [(String,String)] } 
data Response = Response { version :: String, statuscode :: Int } 

instance Show Response where 
    show r = version(r) ++ " " ++ show(statuscode(r)) ++ " " ++ (case statuscode(r) of 
     100 -> "Continue" 
     200 -> "OK" 
     404 -> "Not Found") ++ "\r\n\r\n" 

-- respond function 
respond :: Request -> Handle -> IO() 
respond request handle = do 
    putStrLn $ show request 
    let response = Response {version = "HTTP/1.1", statuscode = 200} 
    hPutStr handle $ show(response) 
    hPutStr handle $ "Haskell says " ++ (getMessage request) 
    where getMessage r 
      | (path r) == "/hello" = "<b>hello there!</b>" <-- HERE 
      | otherwise = (path r) 

我可以運行沒有錯誤的代碼,但是當我訪問http:// {}主機名/你好我得到的字符串<b>hello there!</b>表示html正在呈現爲一個字符串。

如何將其呈現爲html?

注意

我要做到這一點使用香草哈斯克爾,這意味着沒有第三方庫。

+0

您使用的是什麼web框架/庫? – ErikR

+0

請閱讀註釋,沒有框架 – dopatraman

+0

您是否正在發佈Content-type:頭文件?什麼'hPutStr處理$顯示(響應)'實際打印出來? – ErikR

回答

0

您未發出Content-type標頭。如果沒有內容類型標題,瀏覽器可能會將輸出視爲純文本 - 而不是HTML。

如果你改變你的代碼發出:

HTTP/1.1 200 OK 
Content-type: text/html; charset=UTF-8 

Haskell says: <b>hello there!</b> 

應該在瀏覽器中呈現爲HTML。

這SO答案已經包含HTML一個簡單的HTTP響應的例子:

https://stackoverflow.com/a/26346025/866915

更新

基於您的代碼,這應該工作:

response :: Request -> Handle -> IO() 
response _ h = do 
    hPutStr h "HTTP/1.1 200 OK\r\n" 
    hPutStr h "Content-type: text/html; charset=UTF-8\r\n" 
    hPutStr h "\r\n\r\n" 
    hPutStr h "Haskell says: <b>hello there!</b>\n" 

這假設您在發出對的響應後關閉手柄表示響應的結束。此外,請注意,響應的Show實例 並不是非常有用,因爲您必須在HTTP行之後但在空行之前添加更多 標頭。

如果您發佈一個鏈接到您的服務器代碼,我可以爲您測試。

+0

你能發表一個工作的例子嗎? – dopatraman

+0

答案更新 - 如果你發佈一個鏈接到你的服務器代碼,我會測試這個 - 否則我只能假設響應函數是如何工作的。 – ErikR

+0

繼承人鏈接:https://gist.github.com/dopatraman/1573a20f53bf7c5a5d8b25cac9c9d82b – dopatraman