Skip to content

Commit

Permalink
Refactor netstat parsing
Browse files Browse the repository at this point in the history
Move the file hadling into the parseNetstat() function to only open one
file at a time. This eliminates keeping all files open until all are
read.

Signed-off-by: SuperQ <superq@gmail.com>
  • Loading branch information
SuperQ committed May 5, 2023
1 parent 99b481d commit bad5514
Showing 1 changed file with 11 additions and 15 deletions.
26 changes: 11 additions & 15 deletions netstat.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ package procfs

import (
"bufio"
"io"
"os"
"path/filepath"
"strconv"
Expand All @@ -38,13 +37,7 @@ func (fs FS) NetStat() ([]NetStat, error) {
var netStatsTotal []NetStat

for _, filePath := range statFiles {
file, err := os.Open(filePath)
if err != nil {
return nil, err
}
defer file.Close()

procNetstat, err := parseNetstat(file)
procNetstat, err := parseNetstat(filePath)
if err != nil {
return nil, err
}
Expand All @@ -57,14 +50,17 @@ func (fs FS) NetStat() ([]NetStat, error) {

// parseNetstat parses the metrics from `/proc/net/stat/` file
// and returns a NetStat structure.
func parseNetstat(r io.Reader) (NetStat, error) {
var (
scanner = bufio.NewScanner(r)
netStat = NetStat{
Stats: make(map[string][]uint64),
}
)
func parseNetstat(filePath string) (NetStat, error) {
netStat := NetStat{
Stats: make(map[string][]uint64),
}
file, err := os.Open(filePath)
if err != nil {
return netStat, err
}
defer file.Close()

scanner := bufio.NewScanner(file)
scanner.Scan()

// First string is always a header for stats
Expand Down

0 comments on commit bad5514

Please sign in to comment.