get system boot time in go

To get the system boot time in Go, we need to use the syscall.Sysinfo_t struct from the syscall package to retrieve system information, including the boot time. We can use the Uptime field of the struct to get the number of seconds since the system was booted, and then subtract that value from the current Unix time (in seconds) using the time.Now() function to get the actual boot time.

Here's an example code snippet that demonstrates how to get the system boot time in Go:

main.go
package main

import (
    "fmt"
    "syscall"
    "time"
)

func main() {
    var info syscall.Sysinfo_t
    if err := syscall.Sysinfo(&info); err != nil {
        panic(err)
    }

    bootTime := time.Now().Add(-time.Duration(info.Uptime) * time.Second)
    fmt.Println("System boot time:", bootTime)
}
306 chars
18 lines

In this code, we first create a syscall.Sysinfo_t struct variable called info. We then call the syscall.Sysinfo() function to get the system information and store it in the info variable.

Next, we calculate the boot time by calling time.Now() to get the current time, and then subtracting the number of seconds since the system was booted (stored in the Uptime field of the info struct) using the time.Duration() function to convert it into a time.Duration value.

Finally, we print the boot time using the fmt.Println() function.

related categories

gistlibby LogSnag