Skip to content

Commit

Permalink
Make toHeader total (instead of failing when decoding)
Browse files Browse the repository at this point in the history
  • Loading branch information
berdario committed Jul 23, 2016
1 parent d08ae5f commit 5391e54
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 3 deletions.
8 changes: 5 additions & 3 deletions Web/HttpApiData/Internal.hs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import Control.Applicative
import Data.Traversable (Traversable(traverse))
#endif
import Control.Arrow ((&&&))
import Control.Monad ((<=<))
import Data.Either.Combinators (mapLeft)

import Data.Monoid
import Data.ByteString (ByteString)
Expand All @@ -23,7 +25,7 @@ import Data.Int
import Data.Word

import Data.Text (Text)
import Data.Text.Encoding (encodeUtf8, decodeUtf8)
import Data.Text.Encoding (encodeUtf8, decodeUtf8')
import Data.Text.Read (signed, decimal, rational, Reader)
import qualified Data.Text as T
import qualified Data.Text.Lazy as L
Expand Down Expand Up @@ -73,7 +75,7 @@ class FromHttpApiData a where

-- | Parse HTTP header value.
parseHeader :: ByteString -> Either Text a
parseHeader = parseUrlPiece . decodeUtf8
parseHeader = parseUrlPiece <=< (mapLeft (T.pack . show) . decodeUtf8')

-- | Parse query param value.
parseQueryParam :: Text -> Either Text a
Expand Down Expand Up @@ -331,7 +333,7 @@ parseBoundedQueryParam = parseBoundedEnumOfI toQueryParam
-- Uses @'toHeader'@ to get possible values.
parseBoundedHeader :: (ToHttpApiData a, Bounded a, Enum a) => ByteString -> Either Text a
parseBoundedHeader bs = case lookupBoundedEnumOf toHeader bs of
Nothing -> defaultParseError (decodeUtf8 bs)
Nothing -> defaultParseError $ T.pack $ show bs
Just x -> return x

-- | Parse URL piece using @'Read'@ instance.
Expand Down
2 changes: 2 additions & 0 deletions http-api-data.cabal
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ library
, bytestring
, time
, time-locale-compat >=0.1.1.0 && <0.2
, either
if flag(use-text-show)
cpp-options: -DUSE_TEXT_SHOW
build-depends: text-show >= 2
Expand All @@ -46,6 +47,7 @@ test-suite spec
, http-api-data
, text
, time
, bytestring

test-suite doctest
build-depends: base, doctest, Glob
Expand Down
4 changes: 4 additions & 0 deletions test/Spec.hs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import Data.Word
import Data.Time
import qualified Data.Text as T
import qualified Data.Text.Lazy as L
import qualified Data.ByteString as BS
import Data.Version

import Test.Hspec
Expand Down Expand Up @@ -126,3 +127,6 @@ spec = do
parseUrlPieceMaybe (T.pack "256") `shouldBe` (Nothing :: Maybe Int8)
parseUrlPieceMaybe (T.pack "-10") `shouldBe` (Nothing :: Maybe Word)

it "invalid utf8 is handled" $ do
parseHeaderMaybe (BS.pack [128]) `shouldBe` (Nothing :: Maybe T.Text)

0 comments on commit 5391e54

Please sign in to comment.