Parse dynamic String into HostPreference

83 Views Asked by At

Using the Warp library, the setHost function will not accept a dynamic String as a host value, however it will be perfectly happy with a string literal:

> import           Network.Wai.Handler.Warp

> apiHost = "0.0.0.0" :: String
> getHost $ setHost (read apiHost) defaultSettings
*** Exception: Prelude.read: no parse

> getHost $ setHost apiHost defaultSettings
<interactive>:16:19: error:
    • Couldn't match type ‘[Char]’ with ‘HostPreference’
      Expected type: HostPreference
        Actual type: String

> getHost $ setHost "0.0.0.0" defaultSettings
Host "0.0.0.0"

All works fine when the value is a string literal, but I couldn't find any way to make it work when it's a string dynamically generated. Which is exactly what I need, because the host value comes from an environment variable.

2

There are 2 best solutions below

0
On BEST ANSWER

I see you found an answer for this library specifically, but there is a more general solution. You were able to use a string literal because HostPreference is an instance of the IsString class (and you have the OverloadedStrings extension turned on). That means you have the fromString method of that class available, so fromString (read apiHost) should work.

0
On

Turned out... as usual, Hoogle is our friend.

String -> HostPreference

-- first result:
-- Host :: String -> HostPreference
-- streaming-commons Data.Streaming.Network.Internal

And from there

> import           Data.Streaming.Network.Internal (HostPreference (Host))

> apiHost = "0.0.0.0" :: String
> getHost $ setHost (Host apiHost) defaultSettings
Host "0.0.0.0"