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

前端 未结 2 1428
猫巷女王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)
    

提交回复
热议问题