Getting Started
To obtain CPU and RAM usage information in Go, you'll use packages available within the Go ecosystem. One of the most popular packages for system monitoring is gopsutil. This package is mature and offers a wide range of capabilities for retrieving system information.
Installation
First, you need to install the gopsutil package. Run the following command in your terminal:
go get github.com/shirou/gopsutil/v3/...Accessing CPU Information
To get CPU information such as the number of cores, CPU usage, etc., you can use the cpu package provided by gopsutil. Here's how you can do it:
package main
import (
"fmt"
"log"
"github.com/shirou/gopsutil/v3/cpu"
)
func main() {
// Get CPU Info
info, err := cpu.Info()
if err != nil {
log.Fatal(err)
}
for _, ci := range info {
fmt.Printf("CPU Info: %+v\n", ci)
}
// Get CPU Percentage
percentages, err := cpu.Percent(0, true)
if err != nil {
log.Fatal(err)
}
fmt.Printf("CPU Percentages: %+v\n", percentages)
}Accessing RAM Information
To retrieve information about the system's memory such as total, free, and used RAM, you can use the mem package. Below is an example of how to fetch these details:
package main
import (
"fmt"
"log"
"github.com/shirou/gopsutil/v3/mem"
)
func main() {
// Get Memory Info
virtualMemory, err := mem.VirtualMemory()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Total RAM: %v bytes\n", virtualMemory.Total)
fmt.Printf("Free RAM: %v bytes\n", virtualMemory.Free)
fmt.Printf("Used RAM: %v bytes\n", virtualMemory.Used)
fmt.Printf("Used percent: %f%%\n", virtualMemory.UsedPercent)
}Full Example
Here is a complete example combining both CPU and RAM information retrieval:
package main
import (
"fmt"
"log"
"github.com/shirou/gopsutil/v3/cpu"
"github.com/shirou/gopsutil/v3/mem"
)
func main() {
// Get CPU Info
info, err := cpu.Info()
if err != nil {
log.Fatal(err)
}
for _, ci := range info {
fmt.Printf("CPU Info: %+v\n", ci)
}
// Get CPU Percentage
percentages, err := cpu.Percent(0, true)
if err != nil {
log.Fatal(err)
}
fmt.Printf("CPU Percentages: %+v\n", percentages)
// Get Memory Info
virtualMemory, err := mem.VirtualMemory()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Total RAM: %v bytes\n", virtualMemory.Total)
fmt.Printf("Free RAM: %v bytes\n", virtualMemory.Free)
fmt.Printf("Used RAM: %v bytes\n", virtualMemory.Used)
fmt.Printf("Used percent: %f%%\n", virtualMemory.UsedPercent)
}Conclusion
By incorporating the gopsutil package, you can effectively monitor and gather data on system resources such as CPU and memory. This can be useful for logging, alerts, or even displaying system health within a custom application.