Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid converting among different 'string' types in haskell, using snapframework?

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?

like image 699
wenlong Avatar asked Nov 18 '11 14:11

wenlong


1 Answers

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.

like image 102
mightybyte Avatar answered Sep 23 '22 11:09

mightybyte