Sometimes the representation of a value as a request parameter will
be different from its representation expected by Read. In
these cases, we might instead use the FromData
class:
#ifdef HsColour
> class FromData a where
> fromData :: RqData a
#endif
In this example we create a type Vote with a FromData instance:
> module Main where
>
> import Control.Applicative ((<$>), (<*>))
> import Happstack.Server (ServerPart, badRequest, nullConf, ok, simpleHTTP)
> import Happstack.Server.RqData (RqData, lookRead, getDataFn)
>
> data Vote = Yay | Nay deriving (Eq, Ord, Read, Show, Enum, Bounded)
>
> instance FromData Vote where
> fromData =
> do s <- look ""
>
> lookInt :: RqData Int
> lookInt = lookRead "int"
>
> intPart :: ServerPart String
> intPart =
> do r <- getDataFn myPolicy lookInt
> case r of
> (Left e) ->
> badRequest $ unlines e
> (Right i) ->
> ok $ "Read the int: " ++ show i
>
> main :: IO ()
> main = simpleHTTP nullConf $ intPart
[Source code for the app is here.]
Now if we visit http://localhost:8000/?int=1, we will get the message:
Read the int: 1
If we visit http://localhost:8000/?int=apple, we will get the error:
Read failed while parsing: apple