単一URLでクライアントによってHTMLとJSONを切り替える
プログラム例
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DeriveGeneric #-}
import Yesod
import GHC.Generics
import Data.Text (Text)
data Person = Person
{ name :: Text
, age :: Int
} deriving (Generic)
instance ToJSON Person
data App = App
mkYesod "App" [parseRoutes|
/ HomeR GET
|]
instance Yesod App
getHomeR :: Handler TypedContent
getHomeR = selectRep $ do
provideRep $ defaultLayout [whamlet|Hello, my name is #{name} and I am #{age} years old.|]
provideJson person
where
name = "Saito"
age = 29
person = Person name age
main :: IO ()
main = warp 3000 App
プログラム例の実行結果
HTMLを要求した場合
> curl localhost:3000 -H "accept: text/html"
<!DOCTYPE html>
<html><head><title></title></head><body>Hello, my name is Saito and I am 29 years old.</body></html>
JSONを要求した場合
> curl localhost:3000 -H "accept: application/json"
{"age":29,"name":"Saito"}