//go:build linux package memory import ( "bufio" "fmt" "os" "regexp" "strconv" "strings" ) var numberRegex *regexp.Regexp = regexp.MustCompile(`\d+`) func getLinuxRamInfo() (MemoryInformation, error) { memoryFile, err := os.Open("/proc/meminfo") if err != nil { return MemoryInformation{}, fmt.Errorf("Could not find /proc/meminfo. Are you sure you are on linux?") } defer memoryFile.Close() fileReader := bufio.NewScanner(memoryFile) var TotalMemory uint64 var AvailMemory uint64 for fileReader.Scan() { line := fileReader.Text() if strings.HasPrefix(line, "MemTotal:") { TotalMemory, err = strconv.ParseUint(numberRegex.FindString(line), 10, 64) if err != nil { return MemoryInformation{}, fmt.Errorf("Could not parse total memory from /proc/meminfo") } } else if strings.HasPrefix(line, "MemAvailable:") { AvailMemory, err = strconv.ParseUint(numberRegex.FindString(line), 10, 64) if err != nil { return MemoryInformation{}, fmt.Errorf("Could not parse available memory from /proc/meminfo") } } if TotalMemory > 0 && AvailMemory > 0 { break } } if fileReader.Err() != nil { return MemoryInformation{}, fmt.Errorf("There was an error while reading /proc/meninfo. Error: %v", fileReader.Err()) } return MemoryInformation{ SystemMemory: TotalMemory * 1024, AvailableMemory: AvailMemory * 1024, }, nil } func GetRamInformation() (MemoryInformation, error) { return getLinuxRamInfo() }