aboutsummaryrefslogtreecommitdiff
path: root/servant/src/Main.hs
diff options
context:
space:
mode:
authorGregor Kleen <gkleen@yggdrasil.li>2015-10-17 02:26:25 +0200
committerGregor Kleen <gkleen@yggdrasil.li>2015-10-17 02:26:25 +0200
commit005dc408dc09c3b479398ebe3e92efa2cd54846e (patch)
tree23dcfe7a545885c9aa145f1ccae6d33206a87820 /servant/src/Main.hs
parent2dcbb4482de2c352b76372b389fda20c63075295 (diff)
downloadthermoprint-005dc408dc09c3b479398ebe3e92efa2cd54846e.tar
thermoprint-005dc408dc09c3b479398ebe3e92efa2cd54846e.tar.gz
thermoprint-005dc408dc09c3b479398ebe3e92efa2cd54846e.tar.bz2
thermoprint-005dc408dc09c3b479398ebe3e92efa2cd54846e.tar.xz
thermoprint-005dc408dc09c3b479398ebe3e92efa2cd54846e.zip
Working prototype
Diffstat (limited to 'servant/src/Main.hs')
-rw-r--r--servant/src/Main.hs71
1 files changed, 70 insertions, 1 deletions
diff --git a/servant/src/Main.hs b/servant/src/Main.hs
index e9e1deb..9d88559 100644
--- a/servant/src/Main.hs
+++ b/servant/src/Main.hs
@@ -1,2 +1,71 @@
1{-# LANGUAGE RecordWildCards, OverloadedStrings #-}
2
3import Thermoprint
4import Thermoprint.Api
5
6import Data.Aeson
7import Network.Wai
8import Network.Wai.Handler.Warp
9import Servant
10import qualified Data.Text.Lazy as Text
11import qualified Data.ByteString.Lazy.Char8 as ByteString
12import Data.ByteString.Lazy.Char8 (ByteString)
13import GHC.Generics
14
15import Control.Monad
16import Control.Monad.IO.Class
17import Control.Monad.Trans.Either
18
19import Options.Applicative
20
21import System.IO
22
23server :: Options -> Integer -> Block String -> EitherT ServantErr IO ()
24server Options{..} printerNo printOut = do
25 printerPath <- case genericIndex printers printerNo of
26 Just path -> return path
27 Nothing -> left $ err404 { errBody = "printerId out of bounds" }
28 liftIO $ withFile printerPath WriteMode doPrint
29 where
30 doPrint handle = do
31 hSetBuffering handle NoBuffering
32 ByteString.hPut handle $ render' printOut
33 genericIndex :: Integral i => [a] -> i -> Maybe a
34 genericIndex (x:_) 0 = Just x
35 genericIndex (_:xs) n
36 | n > 0 = genericIndex xs (n - 1)
37 | otherwise = Nothing
38 genericIndex _ _ = Nothing
39
40data Options = Options
41 { port :: Int
42 , printers :: [FilePath]
43 }
44
45options :: Parser Options
46options = Options
47 <$> option auto (
48 long "port"
49 <> short 'p'
50 <> metavar "PORT"
51 <> help "The port we'll run the server on"
52 <> value 8080
53 <> showDefault
54 )
55 <*> some (strArgument (
56 metavar "PATH [...]"
57 <> help "Path to one of the printers to use"
58 ))
59
60thermoprintApi :: Proxy ThermoprintApi
61thermoprintApi = Proxy
62
1main :: IO () 63main :: IO ()
2main = undefined 64main = do
65 execParser opts >>= main'
66 where
67 opts = info (helper <*> options) (
68 fullDesc
69 <> header "thermoprint-servant - A REST server for interacting with a cheap thermoprinter"
70 )
71 main' args@(Options{..}) = run port $ serve thermoprintApi (server args)