Skip to main content

Overview

gopsutil is designed as a pure Go port of Python’s psutil library, providing system and process information across multiple operating systems without using cgo. This architecture ensures portability, ease of deployment, and consistent behavior across platforms.

Core Design Principles

Pure Go Implementation

All functionality is implemented without cgo by porting C structs to Go structs, ensuring easy cross-compilation and deployment.

Cross-Platform Support

Supports Linux, Windows, macOS, FreeBSD, OpenBSD, Solaris, and AIX with consistent APIs across platforms.

Context-Aware

All functions support Go’s context.Context for cancellation, timeouts, and passing configuration.

Minimal Dependencies

Uses only Go standard library and platform-specific syscalls to minimize external dependencies.

Package Structure

gopsutil is organized into focused packages, each handling a specific aspect of system information:
Provides CPU times, counts, percentages, and detailed CPU information including vendor, model, and features.
import "github.com/shirou/gopsutil/v4/cpu"

// Get CPU times
times, _ := cpu.Times(false)

// Get CPU info
info, _ := cpu.Info()
Retrieves virtual and swap memory statistics including total, available, used, and percentages.
import "github.com/shirou/gopsutil/v4/mem"

// Get virtual memory stats
v, _ := mem.VirtualMemory()
fmt.Printf("Used: %.2f%%\n", v.UsedPercent)
Handles disk partitions, usage, and I/O counters for storage devices.
import "github.com/shirou/gopsutil/v4/disk"

// Get disk usage
usage, _ := disk.Usage("/")

// Get I/O counters
ioCounters, _ := disk.IOCounters()
Provides system-level information including hostname, uptime, boot time, platform, and virtualization details.
import "github.com/shirou/gopsutil/v4/host"

// Get host info
info, _ := host.Info()
fmt.Printf("Platform: %s\n", info.Platform)
Offers comprehensive process information and control including CPU, memory, I/O, and process lifecycle.
import "github.com/shirou/gopsutil/v4/process"

// Create process instance
p, _ := process.NewProcess(pid)

// Get process info
name, _ := p.Name()
cpuPercent, _ := p.CPUPercent()
Retrieves network interface statistics, connections, and protocol information.
import "github.com/shirou/gopsutil/v4/net"

// Get network I/O counters
counters, _ := net.IOCounters(true)

// Get connections
conns, _ := net.Connections("tcp")
Provides system load averages (1, 5, and 15 minutes) on supported platforms.
import "github.com/shirou/gopsutil/v4/load"

// Get load averages
avg, _ := load.Avg()
fmt.Printf("Load: %.2f %.2f %.2f\n", avg.Load1, avg.Load5, avg.Load15)

Platform-Specific Implementations

1

Cross-Platform Abstraction

Each package defines common interfaces and types that work across all platforms.
// Common type definition in host/host.go
type InfoStat struct {
    Hostname             string
    Uptime               uint64
    BootTime             uint64
    OS                   string
    Platform             string
    PlatformFamily       string
    PlatformVersion      string
    // ...
}
2

Platform-Specific Files

Implementation details are handled in platform-specific files using build tags.
// host_linux.go
//go:build linux

func BootTimeWithContext(ctx context.Context) (uint64, error) {
    return common.BootTimeWithContext(ctx, enableBootTimeCache)
}
3

Common Utilities

The internal/common package provides shared utilities for file reading, path handling, and environment variables.
// Common utility functions
func HostProc(combineWith ...string) string {
    return GetEnv("HOST_PROC", "/proc", combineWith...)
}

Platform-Specific Extensions (Ex Structs)

Starting from v4.24.5, gopsutil provides Ex structs for accessing platform-specific information that isn’t available across all operating systems.
Different platforms expose unique system information. The Ex structures allow you to access this data:
import "github.com/shirou/gopsutil/v4/mem"

ex := mem.NewExLinux()
v, err := ex.VirtualMemory()
if err != nil {
    panic(err)
}

// Access Linux-specific fields
fmt.Println(v.Buffers)
fmt.Println(v.Cached)
The Ex pattern makes it explicit that you’re using platform-specific functionality, helping you write more maintainable code when cross-platform compatibility isn’t required.

Data Flow Architecture

The typical data flow in gopsutil follows this pattern:
1

API Call

User calls a function like mem.VirtualMemory() or cpu.Info()
2

Context Wrapper

The function typically wraps a WithContext variant, passing context.Background()
3

Platform Dispatch

Build tags route to the appropriate platform-specific implementation
4

System Access

Implementation reads from /proc, /sys, or makes syscalls based on platform
5

Data Return

Parsed data is returned as strongly-typed Go structs

Error Handling

gopsutil uses standard Go error handling patterns:
v, err := mem.VirtualMemory()
if err != nil {
    // Handle error
    log.Printf("Failed to get memory info: %v", err)
    return
}

// Use v
fmt.Printf("Total: %v, Used: %.2f%%\n", v.Total, v.UsedPercent)
Some operations may return ErrNotImplementedError on platforms where the functionality isn’t supported. Always check for this error if you need cross-platform compatibility.

Struct Serialization

All major structs in gopsutil implement String() methods that return JSON representations:
v, _ := mem.VirtualMemory()

// Automatic JSON serialization
fmt.Println(v)
// Output: {"total":16777216000,"available":8388608000,...}

// Manual JSON encoding
jsonData, _ := json.Marshal(v)

Next Steps

Context Usage

Learn how to use context for configuration and control

Environment Variables

Configure system paths for containerized environments

Caching

Understand caching strategies for performance

API Reference

Explore detailed API documentation

Build docs developers (and LLMs) love