@@ -7,6 +7,7 @@
8module Servant.Server where
8module Servant.Server where
10import Data.Proxy
11import Data.Proxy
11import Network.HTTP.Types
12import Network.HTTP.Types
12import Network.Wai
13import Network.Wai
@@ -19,17 +20,62 @@ serve p server = toApplication (route p server)
20toApplication :: RoutingApplication -> Application
21toApplication :: RoutingApplication -> Application
21toApplication ra request respond = do
22toApplication ra request respond = do
22− ra request routingRespond
23+ ra request (routingRespond . routeResult)
24− routingRespond :: Maybe Response -> IO ResponseReceived
25+ routingRespond :: Either RouteMismatch Response -> IO ResponseReceived
25− routingRespond Nothing =
26+ routingRespond (Left NotFound) =
26 respond $ responseLBS notFound404 [] "not found"
27 respond $ responseLBS notFound404 [] "not found"
27− routingRespond (Just response) =
28+ routingRespond (Left WrongMethod) =
29+ respond $ responseLBS methodNotAllowed405 [] "method not allowed"
30+ routingRespond (Right response) =
28 respond response
31 respond response
35+ NotFound -- ^ the usual "not found" error
36+ | WrongMethod -- ^ a more informative "you just got the HTTP method wrong" error
41+-- 'NotFound' <> x = x
42+-- 'WrongMethod' <> _ = 'WrongMethod'
44+instance Monoid RouteMismatch where
47+ NotFound `mappend` x = x
48+ WrongMethod `mappend` _ = WrongMethod
50+-- | A wrapper around @'Either' 'RouteMismatch' a@.
51+newtype RouteResult a =
52+ RR { routeResult :: Either RouteMismatch a }
55+failWith :: RouteMismatch -> RouteResult a
58+succeedWith :: a -> RouteResult a
59+succeedWith = RR . Right
61+isMismatch :: RouteResult a -> Bool
62+isMismatch (RR (Left _)) = True
65+-- | If we get a `Right`, it has precedence over everything else.
67+-- This in particular means that if we could get several 'Right's,
68+-- only the first we encounter would be taken into account.
69+instance Monoid (RouteResult a) where
70+ mempty = RR $ Left mempty
72+ RR (Left x) `mappend` RR (Left y) = RR $ Left (x <> y)
73+ RR (Left _) `mappend` RR (Right y) = RR $ Right y
30type RoutingApplication =
76type RoutingApplication =
31 Request -- ^ the request, the field 'pathInfo' may be modified by url routing
77 Request -- ^ the request, the field 'pathInfo' may be modified by url routing
32− -> (Maybe Response -> IO ResponseReceived) -> IO ResponseReceived
78+ -> (RouteResult Response -> IO ResponseReceived) -> IO ResponseReceived
34class HasServer layout where
80class HasServer layout where
35 type Server layout :: *
81 type Server layout :: *