breve/Application.hs

49 lines
1.3 KiB
Haskell
Raw Normal View History

2015-04-08 12:47:56 +02:00
{-# LANGUAGE OverloadedStrings #-}
module Application where
2015-04-08 22:13:02 +02:00
import Breve.Common
import Breve.UrlTable
2015-04-08 12:47:56 +02:00
import Web.Simple
import Web.Simple.Static
import Web.Simple.Templates
import Web.Frank
import Control.Applicative
import Control.Monad.IO.Class
2015-04-08 13:56:05 +02:00
import Text.Printf
2015-04-08 12:47:56 +02:00
import Data.Maybe
import Data.Aeson
import qualified Data.ByteString.Lazy.Char8 as BL
import qualified Data.ByteString.Char8 as BS
app :: (Application -> IO ()) -> IO ()
app runner = do
2015-04-08 15:54:06 +02:00
settings <- newAppSettings
(baseUrl,_) <- serverSettings
table <- records
2015-04-08 12:47:56 +02:00
runner $ controllerApp settings $ do
2015-04-08 13:56:05 +02:00
get "/" (render "index.html" ())
get "/main.css" (serveStatic "layouts/main.css")
2015-04-08 12:47:56 +02:00
get "/:word" $ do
word <- queryParam' "word"
url <- liftIO (extract table word)
2015-04-08 13:56:05 +02:00
case url of
Just url -> do
liftIO $ putStrLn (printf "Resolved %s -> %s" word url)
respond $ redirectTo (BS.pack url)
Nothing -> respond notFound
2015-04-08 12:47:56 +02:00
post "/short" $ do
(form, _) <- parseForm
case lookup "url" form of
2015-04-08 13:56:05 +02:00
Just url' -> do
let url = BS.unpack url'
word <- liftIO (insert table url)
liftIO $ putStrLn (printf "Registered %s -> %s " url word)
2015-04-08 15:54:06 +02:00
render "done.html" $ object ["link" .= (baseUrl ++ word)]
2015-04-08 12:47:56 +02:00
Nothing -> respond badRequest