summaryrefslogtreecommitdiff
path: root/input/stdin/stdin.go
blob: 4421741e2c06875d631067b11fd84b1cad9a90a2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package stdin

import (
	"bufio"
	"fmt"
	"io"
	"os"

	"github.com/Shugyousha/stasher/input"
	"github.com/Shugyousha/stasher/registry"
	"github.com/Shugyousha/stasher/work"
)

func init() {
	registry.Inputregistry["stdin"] = New
}

type StdinInput struct {
	retchan chan *work.Work
}

func New(map[string]string) input.Input {
	return &StdinInput{}
}

func (i *StdinInput) Start() chan *work.Work {
	i.retchan = make(chan *work.Work, 100)
	r := bufio.NewReader(os.Stdin)

	go func() {
		for {
			bs, err := r.ReadBytes(byte('\n'))
			if err == io.EOF {
				break
			}

			w := &work.Work{Data: bs}

			if err != nil {
				fmt.Printf("Error when reading input from Stdin: %q", err)
				w.SetError(err)
			}

			i.retchan <- w
		}
		close(i.retchan)
	}()

	return i.retchan
}