get system cpu temperature in go

To get the system CPU temperature in Go, we can use the hwmon package which allows us to access the hardware monitoring sensors on Linux systems. Here's an example code snippet that shows how to get the CPU temperature:

main.go
package main

import (
    "fmt"
    "github.com/d2r2/go-hwmon"
)

func main() {
    // get the first available CPU core temperature sensor
    sensors, err := hwmon.Sensors()
    if err != nil {
        panic(err)
    }
    var cpuTemp uint32
    for _, s := range sensors {
        if s.Type == hwmon.HwmonType_CPU_TEMP {
            cpuTemp, err = s.Get()
            if err != nil {
                panic(err)
            }
            break
        }
    }
    fmt.Printf("CPU temperature: %d°C\n", cpuTemp/1000)
}
520 chars
26 lines

This code snippet first retrieves all available sensors using the hwmon.Sensors() function. Then it iterates over the sensors and checks if the sensor is a CPU temperature sensor. If a CPU temperature sensor is found, it retrieves the temperature value and prints it out. Note that the temperature value returned is in millidegrees Celsius, so we need to divide the value by 1000 to get the actual temperature in degrees Celsius.

gistlibby LogSnag