File: iochan.go

package info (click to toggle)
golang-github-mitchellh-iochan 1.0.0-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 76 kB
  • sloc: makefile: 2
file content (41 lines) | stat: -rw-r--r-- 874 bytes parent folder | download | duplicates (4)
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
package iochan

import (
	"bufio"
	"io"
)

// DelimReader takes an io.Reader and produces the contents of the reader
// on the returned channel. The contents on the channel will be returned
// on boundaries specified by the delim parameter, and will include this
// delimiter.
//
// If an error occurs while reading from the reader, the reading will end.
//
// In the case of an EOF or error, the channel will be closed.
//
// This must only be called once for any individual reader. The behavior is
// unknown and will be unexpected if this is called multiple times with the
// same reader.
func DelimReader(r io.Reader, delim byte) <-chan string {
	ch := make(chan string)

	go func() {
		buf := bufio.NewReader(r)

		for {
			line, err := buf.ReadString(delim)
			if line != "" {
				ch <- line
			}

			if err != nil {
				break
			}
		}

		close(ch)
	}()

	return ch
}