Skip to main content

Introduction

This guide provides detailed, step-by-step instructions for migrating your codebase from gopsutil v3 to v4. Follow these steps to ensure a smooth transition.
Before starting, we recommend reading the v4 Migration Guide for a complete overview of changes.

Prerequisites

1

Check Go version

gopsutil v4 requires Go 1.18 or higher.
go version
If you need to upgrade Go, visit golang.org/dl
2

Backup your code

Create a backup or commit your current working code:
git add .
git commit -m "Pre-v4 migration checkpoint"
3

Review breaking changes

Read through the breaking changes section below to understand what will need updating

Step 1: Update Import Paths

All import paths must change from v3 to v4. This is a required first step.
Use this command to update all imports automatically:
find . -name '*.go' -exec sed -i 's|github.com/shirou/gopsutil/v3|github.com/shirou/gopsutil/v4|g' {} +
For macOS, use:
find . -name '*.go' -exec sed -i '' 's|github.com/shirou/gopsutil/v3|github.com/shirou/gopsutil/v4|g' {} +

Manual Update

If you prefer to update imports manually: Before:
import (
    "github.com/shirou/gopsutil/v3/cpu"
    "github.com/shirou/gopsutil/v3/mem"
    "github.com/shirou/gopsutil/v3/disk"
    "github.com/shirou/gopsutil/v3/host"
    "github.com/shirou/gopsutil/v3/load"
    "github.com/shirou/gopsutil/v3/net"
    "github.com/shirou/gopsutil/v3/process"
)
After:
import (
    "github.com/shirou/gopsutil/v4/cpu"
    "github.com/shirou/gopsutil/v4/mem"
    "github.com/shirou/gopsutil/v4/disk"
    "github.com/shirou/gopsutil/v4/host"
    "github.com/shirou/gopsutil/v4/load"
    "github.com/shirou/gopsutil/v4/net"
    "github.com/shirou/gopsutil/v4/process"
    "github.com/shirou/gopsutil/v4/sensors"  // New package
)

Step 2: Migrate Temperature Functions

Temperature functions have moved from the host package to the new sensors package.

Search for Temperature Usage

Find all uses of temperature functions:
grep -r "host.SensorsTemperatures" . --include="*.go"
grep -r "host.Temperature" . --include="*.go"

Update the Code

Before:
import "github.com/shirou/gopsutil/v3/host"

func getTemperatures() ([]host.TemperatureStat, error) {
    return host.SensorsTemperatures()
}

func getTemperaturesWithContext(ctx context.Context) ([]host.TemperatureStat, error) {
    return host.SensorsTemperaturesWithContext(ctx)
}
After:
import "github.com/shirou/gopsutil/v4/sensors"

func getTemperatures() ([]sensors.TemperatureStat, error) {
    return sensors.Temperatures()
}

func getTemperaturesWithContext(ctx context.Context) ([]sensors.TemperatureStat, error) {
    return sensors.TemperaturesWithContext(ctx)
}

Function Name Changes

v3 Functionv4 Function
host.SensorsTemperatures()sensors.Temperatures()
host.SensorsTemperaturesWithContext()sensors.TemperaturesWithContext()
The return type also changes from host.TemperatureStat to sensors.TemperatureStat

Step 3: Update Process UID/GID Types

process.Uids() and process.Gids() now return []uint32 instead of []int32

Find Affected Code

grep -r "Uids()" . --include="*.go"
grep -r "Gids()" . --include="*.go"

Update Variable Types

Before:
proc, err := process.NewProcess(pid)
if err != nil {
    return err
}

uids, err := proc.Uids()  // Returns []int32
if err != nil {
    return err
}

var currentUID int32 = uids[0]
if currentUID == 0 {
    fmt.Println("Running as root")
}
After:
proc, err := process.NewProcess(pid)
if err != nil {
    return err
}

uids, err := proc.Uids()  // Returns []uint32
if err != nil {
    return err
}

var currentUID uint32 = uids[0]
if currentUID == 0 {
    fmt.Println("Running as root")
}

Common Type Conversion Scenarios

If you need to compare with existing int32 values:
uids, _ := proc.Uids()

// Convert uint32 to int32 if needed for legacy code
var legacyUID int32 = int32(uids[0])

// Or convert your int32 to uint32
var expectedUID int32 = 1000
if uids[0] == uint32(expectedUID) {
    // Match found
}

Step 4: Update Dependencies

Update your go.mod file to use v4:
go get -u github.com/shirou/gopsutil/v4
go mod tidy
This will:
  1. Download the v4 module
  2. Update your go.mod and go.sum files
  3. Remove any unused dependencies

Step 5: Adopt New Ex Structs (Optional)

If you need platform-specific information, consider using the new Ex structs.

When to Use Ex Structs

Use Ex structs when you need:
  • Platform-specific memory metrics (Linux, Windows)
  • Detailed system information not available in cross-platform API
  • Fine-grained control over specific platform features

Linux Example

import "github.com/shirou/gopsutil/v4/mem"

func getLinuxMemoryDetails() error {
    // Create Linux-specific Ex struct
    ex := mem.NewExLinux()
    
    // Get extended memory information
    v, err := ex.VirtualMemory()
    if err != nil {
        return err
    }
    
    // Access Linux-specific fields
    fmt.Printf("Active File: %d\n", v.ActiveFile)
    fmt.Printf("Inactive File: %d\n", v.InactiveFile)
    fmt.Printf("Active Anon: %d\n", v.ActiveAnon)
    fmt.Printf("Inactive Anon: %d\n", v.InactiveAnon)
    fmt.Printf("Unevictable: %d\n", v.Unevictable)
    
    return nil
}

Windows Example

import "github.com/shirou/gopsutil/v4/mem"

func getWindowsMemoryDetails() error {
    // Create Windows-specific Ex struct
    ex := mem.NewExWindows()
    
    // Get extended memory information
    v, err := ex.VirtualMemory()
    if err != nil {
        return err
    }
    
    // Access Windows-specific fields
    fmt.Printf("Virtual Total: %d\n", v.VirtualTotal)
    fmt.Printf("Virtual Avail: %d\n", v.VirtualAvail)
    fmt.Printf("Commit Limit: %d\n", v.CommitLimit)
    fmt.Printf("Commit Total: %d\n", v.CommitTotal)
    
    return nil
}

Platform-Conditional Code

Use build tags for platform-specific code: mem_linux.go:
//go:build linux

package myapp

import "github.com/shirou/gopsutil/v4/mem"

func getExtendedMemory() (interface{}, error) {
    ex := mem.NewExLinux()
    return ex.VirtualMemory()
}
mem_windows.go:
//go:build windows

package myapp

import "github.com/shirou/gopsutil/v4/mem"

func getExtendedMemory() (interface{}, error) {
    ex := mem.NewExWindows()
    return ex.VirtualMemory()
}

Step 6: Test Your Changes

1

Build your project

Ensure the code compiles:
go build ./...
2

Run unit tests

Execute your test suite:
go test ./...
3

Run integration tests

If you have integration tests, run them to verify behavior:
go test -tags=integration ./...
4

Manual testing

Test critical paths manually to ensure everything works as expected

Common Migration Issues

Issue 1: Import Not Found

Error:
package github.com/shirou/gopsutil/v4/sensors is not in GOROOT
Solution: Make sure you’ve run go get to download v4:
go get github.com/shirou/gopsutil/v4

Issue 2: Type Mismatch with UIDs

Error:
cannot use uids[0] (type uint32) as type int32 in assignment
Solution: Update your variable types from int32 to uint32:
// Before
var uid int32 = uids[0]

// After
var uid uint32 = uids[0]

Issue 3: Undefined Function

Error:
host.SensorsTemperatures undefined
Solution: Change to the sensors package:
// Before
import "github.com/shirou/gopsutil/v4/host"
temps, _ := host.SensorsTemperatures()

// After
import "github.com/shirou/gopsutil/v4/sensors"
temps, _ := sensors.Temperatures()

Issue 4: Go Version Too Old

Error:
go: requires go >= 1.18
Solution: Upgrade your Go installation to 1.18 or higher.

Rollback Plan

If you need to rollback to v3:
# Revert import changes
find . -name '*.go' -exec sed -i 's|github.com/shirou/gopsutil/v4|github.com/shirou/gopsutil/v3|g' {} +

# Downgrade dependency
go get github.com/shirou/gopsutil/v3
go mod tidy

# Revert temperature changes
# (You'll need to manually undo sensors -> host changes)

Verification Checklist

Before considering the migration complete:
  • All imports updated from v3 to v4
  • Temperature functions moved to sensors package
  • UID/GID type changes applied
  • Code compiles without errors
  • Unit tests pass
  • Integration tests pass (if applicable)
  • Manual testing completed
  • CI/CD pipeline passes
  • Documentation updated

Next Steps

After successfully migrating:

Explore New Features

Learn about Ex structs and other v4 enhancements

Platform-Specific Features

Leverage platform-specific capabilities

Best Practices

Follow cross-platform development best practices

API Reference

Browse the complete v4 API

Need Help?

If you encounter issues during migration:

Build docs developers (and LLMs) love