Reputation: 1434
I want to produce the decoded result for POST data. Much code is 'wasted' in converting 'string'. That makes code ugly. Any better solutions?
import Codec.Binary.Url (decode')
import qualified Data.ByteString.Lazy.Char8 as L (unpack)
import qualified Data.ByteString.Char8 as S (unpack, pack)
import qualified Data.ByteString.Lazy as LBS (pack)
decodeUrlHandler :: Snap()
decodeUrlHandler = do
body <- readRequestBody (maxBound :: Int64)
writeLBS $ LBS.pack $ map (fromMaybe 0) $ decode' $ L.unpack body
What would your code for this purpose be?
Upvotes: 7
Views: 651
Reputation: 7272
Snap automatically decodes the request and makes it available to you through the Request data type. It provides functions getRequest and withRequest for retrieving the request and a number of other accessor functions for getting various parts.
There are also convenience functions for common operations. To get a POST or GET parameter see getParam.
Snap gives it to you as a ByteString because this API sits at a fairly low level of abstraction, leaving it up to the user how to handle things like text encoding. I would recommend that you use the much more efficient Text type instead of String. The Readable type class also provides a mechanism for eliminating some of the boilerplate of these conversions. The default instances for numbers and Text assume UTF8 encoding.
Upvotes: 9