In this lab, we'll be using the os and bufio packages to read our wordbank from a file on disk. Since reading a file can fail, we will also be learning the most basic error handling strategy.
- Add a new flag "wordbank" that accepts a filepath as a string.
- Modify the
NewWordBank
function to take an *os.File as input - Create a bufio.Scanner by passing the
*os.File
into the bufio.NewScanner constructor.
Note: thebufio.NewScanner
function expects an io.Reader as its input. Fortunately,*os.File
implements theio.Reader
interface. - Loop over the lines in the file and use the builtin append function to add them to your wordbank.
Hint: see this example from the scanner documentation for inspiration. - If
scanner.Err()
is notnil
, call panic on the error value. - Move the words from the old hardcoded slice into a file on disk.
- Modify the
generateIpsum
function to os.Open the file for reading - If the error value returned by
os.Open
is notnil
, callpanic
on the error value defer
the close method on the file object immediately after handling the error.
Hint: see this example from effective go- pass the *os.File instance into the
NewWordbank
function.