

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 5
click for more info
Not enough gems
Cost: 6 gems
1: Welcome to 'Learn the HTTP Protocol'
incomplete
2: TheStartup™
incomplete
3: 8 Bytes
incomplete
4: Newlines
incomplete
5: Channel Refactor
incomplete
This lesson's interactive features are locked, please to keep using them
If you wrote your code like mine, there's a good chance that you've got a little state machine going on directly inside your main function.
Let's refactor our code so that we have a nice reusable function that reads lines from a TCP connection.
func getLinesChannel(f io.ReadCloser) <-chan stringIt should contain all the logic you've already written that keeps track of the current line's contents, reads 8 bytes at a time, etc. The differences are that now:
It creates a channel of strings
It does the reading loop inside a goroutine
It does not prefix the lines with "read: " or add a newline character at the end. Instead, it sends one line at a time to the channel.
The goroutine exits when it reaches the end of the file, and the channel is closed.
The function returns the channel for immediate use by the caller
The function closes the file when it's done reading (don't close it when the channel is returned, that's too early!)
os.File implements io.ReadCloser, so you can pass your file directly to your new function.
Range over the returned channel, and print each line in the same format as before, prefixed with "read: " and followed by a newline.
Your code should behave the same way as before, but now the logic for reading lines is encapsulated in a reusable function.
Run and submit the CLI tests.