I'm pretty new to developing in golang, so if this is an elementary question I apologize. I didn't see a comparable question already asked; if there is one, please point me to it (thanks).
The full code (at the time of my asking this question, since it's not immutable) is at http://play.golang.org/p/idDp1E-vZo
I've declared a struct with four primitive fields, and I'm reading the values destined for Node.ipaddr
from a file on the local filesystem (I'm getting the value of fileName
as a flag at runtime; that code is trimmed out here but is in the link provided above.)
type Node struct {
hostname string
ipaddr string
pstatus string
ppid int
}
file, err := os.Open(fileName)
if err != nil {
panic(fmt.Sprintf("error opening %s: %v", fileName, err))
}
Because the file is line-delimited, I thought a bufio.Scanner
would be ideal for reading the data from the file. Where I am struggling is finding an elegant way to actually pass the data into the struct elements.
I created an array of Node
elements, and have considered a map
, but I am not sure how I'd make practical use of it (yet).
var nodes []*Node
var nodemap = make(map[string]*Node) //do I even need this?
scanner := bufio.NewScanner(file)
for scanner.Scan() {
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "error reading from file:", err)
os.Exit(3)
}
//pass scanner.Text() into Node.ipaddr
}
Short of wrapping scanner.Scan()
in an indexed for
loop, I'm not at all sure how to proceed. If I do wrap scanner.Scan()
in an indexed for
loop, will the for
loop be able to handle EOF elegantly -- I guess I'm not sure what the index limit/max comparison value should be in that case.
As always, thanks for any advice that you're willing to offer.
edit: The format of the input file is like this:
10.1.1.1
10.1.1.2
10.1.1.3
I anticipate approx 150 entries in the file, one IPv4 address per line.