Data.ByteString.Lazy.Internal.ByteString to string?

前端 未结 2 1430
猫巷女王i
猫巷女王i 2021-02-13 14:14

Trying to write a module which returns the external IP address of my computer. Using Network.Wreq get function, then applying a lense to obtain r

相关标签:
2条回答
  • 2021-02-13 14:32

    I simply do not understand why you insist on using Strings, when you have already a ByteString at hand that is the faster/more efficient implementation. Importing regex gives you almost no benefit - for parsing an ip-address I would use attoparsec which works great with ByteStrings.

    Here is a version that does not use regex but returns a String - note I did not compile it for I have no haskell setup where I am right now.

    {-# LANGUAGE OverloadedStrings #-}
    
    module ExtIp (getExtIp) where
    import Network.Wreq
    import Control.Lens
    import Data.ByteString.Lazy.Char8 as Char8
    import Data.Char (isSpace)
    
    getExtIp :: IO String
    getExtIp = do
        r <- get "http://myexternalip.com/raw"
        return $ Char8.unpack $ trim (r ^. responseBody)
      where trim = Char8.reverse . (Char8.dropWhile isSpace) . Char8.reverse . (Char8.dropWhile isSpace)
    
    0 讨论(0)
  • 2021-02-13 14:32

    Short answer: Use unpack from Data.ByteString.Lazy.Char8

    Longer answer:

    In general when you want to convert a ByteString (of any variety) to a String or Text you have to specify an encoding - e.g. UTF-8 or Latin1, etc.

    When retrieving an HTML page the encoding you are suppose to use may appear in the Content-type header or in the response body itself as a <meta ...> tag.

    Alternatively you can just guess at what the encoding of the body is.

    In your case I presume you are accessing a site like http://whatsmyip.org and you only need to parse out your IP address. So without examining the headers or looking through the HTML, a safe encoding to use would be Latin1.

    To convert ByteStrings to Text via an encoding, have a look at the functions in Data.Text.Encoding

    For instance, the decodeLatin1 function.

    0 讨论(0)
提交回复
热议问题