ホーム > Haskell > Yesodで動的サイトを作成する >

ユーザ定義のデータ型を返すハンドラを作成する

プログラム例

{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE OverloadedStrings         #-}
{-# LANGUAGE QuasiQuotes               #-}
{-# LANGUAGE TemplateHaskell           #-}
{-# LANGUAGE TypeFamilies              #-}

import Data.Text (Text)
import Yesod

data Person = Person
    { name :: Text
    , age  :: Int
    } deriving (Show)

data App = App

mkYesod "App" [parseRoutes|
/ HomeR GET
|]

instance Yesod App

mimeType :: ContentType
mimeType = "text/haskell-show"

data HaskellShow = forall a. Show a => HaskellShow a

instance ToContent HaskellShow where
    toContent (HaskellShow x) = toContent $ show x

instance ToTypedContent HaskellShow where
    toTypedContent = TypedContent mimeType . toContent

getHomeR :: Handler HaskellShow
getHomeR =
    return $ HaskellShow person
  where
    person = Person "Saito" 29

main :: IO ()
main = warp 3000 App

プログラム例の実行結果

> curl localhost:3000
Person {name = "Saito", age = 29}