What do you do if you need to get the usage of your host’s hard disk, CPU, memory, processes, etc. in Golang? A simple idea would be to run some commands like ps, cd, top through os/exec and then parse the results of those commands.
Of course, based on the Linux idea that everything is a file, a more straightforward approach would be to read the contents of the relevant files, such as those in the /proc directory.
The above approach can fulfill the requirements, but we don’t have to duplicate the creation of tools, because there is already a fairly well-developed three-way library that implements these collection requirements for us, and it is gopsutil.
Introduction to gopsutil
psutil (process and system utilities,) is a cross-platform library for getting process and system utilization (CPU, memory, disk, network, sensors) information in Python, and gopsutil is the Go language version of it.
gopsutil shields us from the differences between systems. It has good portability.
The following systems are supported.
- FreeBSD i386/amd64/arm
- Linux i386/amd64/arm(raspberry pi)
- Windows i386/amd64/arm/arm64
- Darwin i386/amd64
- OpenBSD amd64
- Solaris amd64
Partial Support List.
- CPU on DragonFly BSD
- host on Linux RISC-V
In addition, by porting C structures to Go structures, the project has no cgo code in its implementation, which makes it easier to cross-compile.
There are v3 and v2 versions of gopsutil available and no backward compatibility guarantees, so there are two ways to use it.
For example, if we want to view system memory usage information, we can get it in the following way.
The results of the run are as follows.
One friendly aspect of the gopsutil package is that most of the collection functions return a structure object, which implements the
fmt.Stringer interface, so they will be output in json format when printed.
For example, the
mem.VirtualMemory example above returns a VirtualMemoryStat structure, which calls the
json.Marshal() function in the
gopsutil is divided into different sub-packages according to different acquisition units, and the relevant methods can be called by introducing different sub-packages in use.
For example, if we want to get the host information, we need to import
the github.com/shirou/gopsutil/v3/host subpackage.
The gopsutil library has very comprehensive coverage units, including host, disk, memory, CPU, network, process, docker and other modules, it can help us get system information very well. And gopsutil handles cross-platform compatibility issues, the external interface is basically consistent and friendly to use.
The library will help you in scenarios such as information gathering, system monitoring, resource limitation, process management, etc.