88{-# LANGUAGE OverloadedStrings #-}
99
1010import Data.Text (Text )
11- import Network.HTTP.Types (ok200 , notFound404 )
12- import Network.HTTP.Types.Header (hContentType )
11+ import Network.HTTP.Types (ok200 , movedPermanently301 , notFound404 )
12+ import Network.HTTP.Types.Header (hContentType , hLocation )
1313import Network.Wai (Application , responseLBS , pathInfo )
1414
15+ import qualified Data.ByteString
16+ import qualified Data.ByteString.Lazy
17+ import qualified Data.Text as Text
18+ import qualified Data.Text.Encoding
19+ import qualified Data.Text.Lazy
20+ import qualified Data.Text.Lazy.Encoding
1521import qualified Network.Wai.Handler.Warp as Warp
1622
23+ -- Strings in Haskell are madness. For url pieces, we get a strict Text. For
24+ -- the response body, we must provide a lazy ByteString, but for the headers a
25+ -- strict ByteString. To alleviate the pain a bit, work with stict Text
26+ -- internally everywhere, and use the two functions below to convert to the
27+ -- required type.
28+
29+ encodeUtf8Lazy :: Text -> Data.ByteString.Lazy. ByteString
30+ encodeUtf8Lazy = Data.Text.Lazy.Encoding. encodeUtf8 . Data.Text.Lazy. fromStrict
31+
32+ encodeUtf8Strict :: Text -> Data.ByteString. ByteString
33+ encodeUtf8Strict = Data.Text.Encoding. encodeUtf8
34+
35+ serveRedirect :: Text -> Application
36+ serveRedirect newUrl request f =
37+ let
38+ body = Text. append " -> " newUrl
39+ headers =
40+ [ (hLocation, encodeUtf8Strict newUrl)
41+ , (hContentType, " text/plain" )
42+ ]
43+ in
44+ f $ responseLBS movedPermanently301 headers (encodeUtf8Lazy body)
45+
1746-- Define the urls.
1847router :: Application
1948router request = case pathInfo request of
@@ -23,10 +52,10 @@ router request = case pathInfo request of
2352
2453-- Serves the GitHub repository redirect.
2554serveRepo :: Text -> Application
26- serveRepo request args f =
27- f $ responseLBS ok200 [(hContentType, " text/plain " )] " should redirect to repository "
55+ serveRepo repo =
56+ serveRedirect $ Text. append " https://github.com/ruuda/ " repo
2857
29- -- Serves the GitHub repository redirect .
58+ -- Serves main page .
3059serveIndex :: Application
3160serveIndex request f =
3261 f $ responseLBS ok200 [(hContentType, " text/plain" )] " hi"
0 commit comments