-
-
Save co-dan/171fbcf6a04c52d28440 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
> {-# LANGUAGE OverloadedStrings #-} | |
> module Main where | |
In this example we will take a look at 'IOWorker' and how to use it in | |
your programs. We will create a simple worker that would echo back to | |
us whatever we sent it. | |
Let's start by importing some libraries | |
> import Control.Concurrent (threadDelay) | |
> import Control.Monad (when) | |
> import qualified Data.ByteString as BS | |
> import Data.Default (def) | |
> import Data.Monoid ((<>)) | |
> import System.IO (BufferMode (..), Handle, hClose, | |
> hSetBuffering, stdin, stdout) | |
> import Worker | |
Let's take a look at 'startIOWorker' function: | |
```haskell | |
startIOWorker :: String -- ^ Name | |
-> LimitSettings -- ^ Restrictions | |
-> FilePath -- ^ UNIX socket | |
-> (Handle -> IO ()) -- ^ Callback | |
-> IO (Worker IOWorker, RestartWorker IO IOWorker) | |
``` | |
it takes a worker name, a UNIX socket filepath, callback. It returns | |
the worker itself together with the restarting function. | |
Firstly, let's implement our callback: | |
> echoHandle :: Handle -> IO () | |
> echoHandle h = do | |
> hSetBuffering h LineBuffering | |
> s <- BS.hGetLine h | |
> BS.putStr $ "Got: " <> s <> "\n" | |
> BS.hPutStr h s | |
> hClose h | |
we are not doing anything fancy here, just getting one line of text, | |
printing it to stdout and sending it back. | |
Now we are going to write the main loop function that would take care | |
of restarting the worker: | |
> loop :: (Worker IOWorker, RestartWorker IO IOWorker) -> IO () | |
> loop (w, restart) = do | |
> putStrLn "Press <ENTER> to restart the worker" | |
> _ <- getChar | |
> w' <- restart w | |
> loop (w', restart) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment