git.iko.soy/typeable/http-api-data
on master help sign in
Make parseHeader total (instead of failing when decoding)
commit6ec0d6c855bf053b2e9686b4dd9409da6073ec25 authorDario Bertini <berdario@gmail.com> dateSat 23 Jul 2016, 15:31 (10 years ago) parentd08ae5f
3 files changed+11−3
Web/HttpApiData/Internal.hs+5−3 http-api-data.cabal+2 test/Spec.hs+4
Web/HttpApiData/Internal.hs+5−3
@@ -14,6 +14,8 @@ import Control.Applicative
1414import Data.Traversable (Traversable(traverse))
1515#endif
1616import Control.Arrow ((&&&))
17+import Control.Monad ((<=<))
18+import Data.Either.Combinators (mapLeft)
1719
1820import Data.Monoid
1921import Data.ByteString (ByteString)
@@ -23,7 +25,7 @@ import Data.Int
2325import Data.Word
2426
2527import Data.Text (Text)
26−import Data.Text.Encoding (encodeUtf8, decodeUtf8)
28+import Data.Text.Encoding (encodeUtf8, decodeUtf8')
2729import Data.Text.Read (signed, decimal, rational, Reader)
2830import qualified Data.Text as T
2931import qualified Data.Text.Lazy as L
@@ -73,7 +75,7 @@ class FromHttpApiData a where
7375
7476 -- | Parse HTTP header value.
7577 parseHeader :: ByteString -> Either Text a
76− parseHeader = parseUrlPiece . decodeUtf8
78+ parseHeader = parseUrlPiece <=< (mapLeft (T.pack . show) . decodeUtf8')
7779
7880 -- | Parse query param value.
7981 parseQueryParam :: Text -> Either Text a
@@ -331,7 +333,7 @@ parseBoundedQueryParam = parseBoundedEnumOfI toQueryParam
331333-- Uses @'toHeader'@ to get possible values.
332334parseBoundedHeader :: (ToHttpApiData a, Bounded a, Enum a) => ByteString -> Either Text a
333335parseBoundedHeader bs = case lookupBoundedEnumOf toHeader bs of
334− Nothing -> defaultParseError (decodeUtf8 bs)
336+ Nothing -> defaultParseError $ T.pack $ show bs
335337 Just x -> return x
336338
337339-- | Parse URL piece using @'Read'@ instance.
http-api-data.cabal+2
@@ -26,6 +26,7 @@ library
2626 , bytestring
2727 , time
2828 , time-locale-compat >=0.1.1.0 && <0.2
29+ , either
2930 if flag(use-text-show)
3031 cpp-options: -DUSE_TEXT_SHOW
3132 build-depends: text-show >= 2
@@ -46,6 +47,7 @@ test-suite spec
4647 , http-api-data
4748 , text
4849 , time
50+ , bytestring
4951
5052test-suite doctest
5153 build-depends: base, doctest, Glob
test/Spec.hs+4
@@ -10,6 +10,7 @@ import Data.Word
1010import Data.Time
1111import qualified Data.Text as T
1212import qualified Data.Text.Lazy as L
13+import qualified Data.ByteString as BS
1314import Data.Version
1415
1516import Test.Hspec
@@ -126,3 +127,6 @@ spec = do
126127 parseUrlPieceMaybe (T.pack "256") `shouldBe` (Nothing :: Maybe Int8)
127128 parseUrlPieceMaybe (T.pack "-10") `shouldBe` (Nothing :: Maybe Word)
128129
130+ it "invalid utf8 is handled" $ do
131+ parseHeaderMaybe (BS.pack [128]) `shouldBe` (Nothing :: Maybe T.Text)
132+