Files
rpi5-health/internal/system_check/linux_ram.go
T
2026-10-05 14:48:43 +02:00

56 lines
1.3 KiB
Go

//go:build linux
package system_check
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?")
}
fileReader := bufio.NewScanner(memoryFile)
var TotalMemory uint64
var AvailMemory uint64
for fileReader.Scan() {
if fileReader.Err() != nil {
return MemoryInformation{}, fmt.Errorf("There was an error while reading /proc/meninfo. Error: %v", fileReader.Err())
}
line := fileReader.Text()
if strings.Contains(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.Contains(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")
}
}
}
return MemoryInformation{
SystemMemory: TotalMemory,
AvailableMemory: AvailMemory,
}, nil
}
func GetRamInformation() (MemoryInformation, error) {
return getLinuxRamInfo()
}