Last active
December 12, 2015 01:08
-
-
Save freeformz/4688206 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
package utils | |
import "fmt" | |
func main() { | |
for line := range FileLineChannel('/etc/hosts') { | |
fmt.Println(line) | |
} | |
} |
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
package utils | |
import ( | |
"log" | |
"bufio" | |
"io" | |
"os" | |
) | |
func FileLineChannel(fpath string) (<-chan string) { | |
c := make(chan string) | |
go func(fpath string, cs chan<- string) { | |
defer close(cs) | |
file, err := os.Open(fpath) | |
if err == nil { | |
defer file.Close() | |
buf := bufio.NewReader(file) | |
for { | |
line, err := buf.ReadString('\n') | |
switch err { | |
case io.EOF: break | |
case nil: cs <- line | |
default: log.Fatal(err) | |
} | |
} | |
} | |
}(fpath, c) | |
return c | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think you need to move the
cs <- line
above your switch as otherwise if the file ends without a newline, you won't send the last line into your channel. (thecase io.EOF
will hit first).