Search code examples
haskellservant

Haskell Servant: return String from file


I have the following API:

type ServerAPI =
    "getBoard" :> Get '[JSON] String


serverRoutes :: Server ServerAPI
serverRoutes = 
    return (readFile "src/board.txt")

What I need to do is read a file and then return its content as the response for the request at "getBoard" route. It has proven to be very difficult, since readFile returns a IO String, not a String. Already looked for ways of returning a String from readFile and what I've found was this:

convertToString :: String -> String
convertToString str = str


type ServerAPI =
    "getBoard" :> Get '[JSON] String


serverRoutes :: Server ServerAPI
serverRoutes = do
    contents <- readFile "src/board.txt"
    let x = convertToString contents
    return x

But it keeps saying to me that serverRoutes is returning a IO String. I'm not sure if I'm doing the convertToString wrong or if the problem is with the do at serverRoutes. Any help would be appreciated.


Solution

  • The monad you're in isn't IO, but it is an instance of MonadIO, so you use liftIO, like this:

    serverRoutes :: Server ServerAPI
    serverRoutes = liftIO $ readFile "src/board.txt"