Overview
gopsutil provides a unified API across different operating systems while handling platform-specific implementations internally. This guide shows you how to work with cross-platform code and handle platform differences in your applications.Understanding Platform-Specific Files
gopsutil uses Go’s build tag system to compile different implementations for each platform. Files are organized with platform-specific suffixes:Build Tags
Platform-specific files use build tags at the top:cpu_linux.go
cpu_fallback.go
Writing Cross-Platform Applications
Use Context-Aware Functions
Always prefer functions that acceptcontext.Context for better control:
Handle Platform Differences
Some fields are platform-specific. Check availability before using them:Runtime Detection
Useruntime.GOOS to detect the platform at runtime:
Handling Unsupported Features
Check for Not Implemented Errors
On unsupported platforms, functions returncommon.ErrNotImplementedError:
Graceful Degradation
Design your application to degrade gracefully when features aren’t available:Testing Across Platforms
Use Build Tags in Tests
Write platform-specific tests using build tags:cpu_linux_test.go
Mock Platform Detection
For unit tests, consider abstracting platform detection:Environment Variables for Testing
gopsutil supports environment variables to override system paths (useful for testing):HOST_PROC
Override
/proc directory (Linux)HOST_SYS
Override
/sys directory (Linux)HOST_ETC
Override
/etc directoryHOST_VAR
Override
/var directoryBest Practices
Always use context-aware functions
Use
*WithContext variants for better control and cancellation support.Platform Support Matrix
| Feature | Linux | macOS | Windows | FreeBSD | Others |
|---|---|---|---|---|---|
| CPU Info | ✅ | ✅ | ✅ | ✅ | ⚠️ |
| CPU Times | ✅ | ✅ | ✅ | ✅ | ❌ |
| Memory Info | ✅ | ✅ | ✅ | ✅ | ✅ |
| Disk Usage | ✅ | ✅ | ✅ | ✅ | ✅ |
| Process Info | ✅ | ✅ | ✅ | ✅ | ⚠️ |
| Network Stats | ✅ | ✅ | ✅ | ✅ | ⚠️ |
Related Resources
Error Handling
Learn how to handle errors across platforms
Performance
Optimize performance for each platform