如何使用Template Haskell在編譯時使用isURI
驗證靜態URL?現在在運行時使用fromJust
是安全的,因爲URL必須是有效的。
例如,像這樣定義staticURI
。
{-# LANGUAGE TemplateHaskell #-}
module URI where
import Data.Maybe (fromJust)
import Network.URI (URI, isURI, parseURI)
import Language.Haskell.TH (Q, TExp)
staticURI :: String -> Q (TExp URI)
staticURI uri | isURI uri = [|| fromJust $ parseURI uri ||]
| otherwise = fail $ "Invalid URI: " ++ uri
然後,你可以在這樣的其他模塊中定義你的URL。
{-# LANGUAGE TemplateHaskell #-}
import Network.URI (URI)
import URI (staticURI)
url :: URI
url = $$(staticURI "http://www.google.com/")
badUrl :: URI
badUrl = $$(staticURI "http://www.google.com/##")
當你傳遞了錯誤的URL來staticURI
,編譯器會發出錯誤。
Invalid URI: http://www.google.com/##
In the Template Haskell splice
$$(staticURI "http://www.google.com/##")
In the expression: $$(staticURI "http://www.google.com/##")
In an equation for ‘url’:
url = $$(staticURI "http://www.google.com/##")