Golang populates the structure field from a file

I am new to the development of the Golang, so if this is an elementary question, I apologize. I have not seen a comparable question; if there is, indicate me (thanks).

The full code (at the time of my request for this question, as it is not immutable) is at http://play.golang.org/p/idDp1E-vZo

I declared a structure with four primitive fields, and I read the values ​​intended for Node.ipaddrfrom a file on the local file system (I get the value fileNameas a flag at runtime; this code is truncated here, but is located in the link 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))
}

, , bufio.Scanner . , , .

Node map, , ().

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

}

scanner.Scan() for, , . scanner.Scan() for, for EOF - , , / .

, , .

edit. :

10.1.1.1
10.1.1.2
10.1.1.3

150 , IPv4- .

+4
2

, - append, node .

nodes = append(nodes, &Node{ipaddr: scanner.Text()})

, for, scanner.Scan() . EOF , Node, .

for i := 0; scanner.Scan(); i++ {
    if err := scanner.Err(); err != nil {
        fmt.Fprintln(os.Stderr, "error reading from file:", err)
        os.Exit(3)
    }

    nodes = append(nodes, &Node{ipaddr: scanner.Text()})
    fmt.Println(nodes[i])
}

: http://play.golang.org/p/RvMQp-jgWF

+2

- this:

func main() {
    file := strings.NewReader(IPS) //os.Open(fileName)

    var nodes []*Node

    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)
        }
        ip := net.ParseIP(scanner.Text())
        if ip != nil {
            nodes = append(nodes, &Node{ipaddr: net.ParseIP(scanner.Text())})
        }

    }
    for _, n := range nodes {
        fmt.Printf("%s, %+v\n", n.ipaddr, n)
    }
}
+2

Source: https://habr.com/ru/post/1540601/


All Articles