File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11package main
22
3- import "fmt"
3+ import (
4+ "fmt"
5+ "io"
6+ "os"
7+ "strings"
8+ )
9+
10+ func getLinesChannel (f io.ReadCloser ) <- chan string {
11+ lines := make (chan string )
12+
13+ go func () {
14+ defer f .Close ()
15+ defer close (lines )
16+
17+ currentLine := ""
18+
19+ for {
20+ read := make ([]byte , 8 )
21+ _ , err := f .Read (read )
22+
23+ if err == io .EOF {
24+ // Send the last line if it has content
25+ if currentLine != "" {
26+ lines <- currentLine
27+ }
28+ return
29+ }
30+
31+ if err != nil {
32+ fmt .Println ("Some Error Happened While Putting in Slice" )
33+ return
34+ }
35+
36+ parts := strings .Split (string (read ), "\n " )
37+
38+ // Process all parts except the last one, which may be incomplete
39+ if len (parts )- 1 > 0 {
40+ currentLine += parts [0 ]
41+ lines <- currentLine
42+ currentLine = "" // Reset for next line
43+ }
44+
45+ // The last part, which may be incomplete gets added to currentLine
46+ currentLine += parts [len (parts )- 1 ]
47+ }
48+ }()
49+
50+ return lines
51+ }
452
553func main () {
6- fmt .Println ("Starting Out" )
54+ file , err := os .Open ("./messages.txt" )
55+
56+ if err != nil {
57+ fmt .Println ("Error Happend" , err .Error ())
58+ }
59+
60+ lines := getLinesChannel (file )
61+
62+ for val := range lines {
63+ fmt .Println ("read: " , val )
64+ }
65+
66+ fmt .Println ("DONE" )
767}
You can’t perform that action at this time.
0 commit comments