Links und Funktionen
Sprachumschaltung

Navigationspfad


Inhaltsbereich

Yesod Session

Code Beispiel für die Standard Sitzungsverwaltung von Yesod

Haskell source code icon YesodSession.hs — Haskell source code, 1 KB (1703 bytes)

Dateiinhalt

-- Source: Yesod Web Framework Book- Version 1.4 
-- http://www.yesodweb.com/book
-- (small modifications possible)
{-# LANGUAGE OverloadedStrings     #-}
{-# LANGUAGE QuasiQuotes           #-}
{-# LANGUAGE TemplateHaskell       #-}
{-# LANGUAGE TypeFamilies          #-}
{-# LANGUAGE MultiParamTypeClasses #-}
import           Control.Applicative ((<$>), (<*>))
import qualified Web.ClientSession   as CS
import           Yesod
import           Data.Text (pack,unpack)
import qualified Data.Map as Map

data App = App

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

instance Yesod App where
    -- Make the session timeout 1 minute so that it's easier to play with
    makeSessionBackend _ = Just <$> defaultClientSessionBackend 1 "keyfile.aes"

instance RenderMessage App FormMessage where
    renderMessage _ _ = defaultFormMessage

getHomeR :: Handler Html
getHomeR = do
    sess <- getSession
    msg  <- getMessage
    defaultLayout
        [whamlet|
            <form method=post>
                <input type=text name=key>
                <input type=text name=val>
                <input type=submit>
            <h1>
              <ul>
                $forall kv <- Map.toList sess
                  <li> #{show kv}
            <h1>
              $maybe m <- msg 
                Message: #{m}
        |]

postHomeR :: Handler ()
postHomeR = do
    (key, mval) <- runInputPost $ (,) <$> ireq textField "key" <*> iopt textField "val"
    case mval of
        Nothing  -> deleteSession key
        Just val -> setSession key val
    liftIO $ print (key, mval) --debug to konsole
    setMessage $ toHtml $ "Just set: " ++ show (key, mval)
    redirect HomeR

main :: IO ()
main = warp 3000 App

Artikelaktionen


Funktionsleiste