We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Channel Refactor

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.

Assignment

  1. func getLinesChannel(f io.ReadCloser) <-chan string
    
    It 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.