restart the computer in go

To restart the computer in Go, you can use the exec.Command function to execute the appropriate system call. On Unix/Linux systems, you can use the shutdown command with appropriate arguments to restart the system. On Windows systems, you can use the shutdown command with /r argument to restart the system.

Here is an example code:

main.go
package main

import (
    "log"
    "os/exec"
    "runtime"
)

func main() {
    var cmd *exec.Cmd
    if runtime.GOOS == "windows" {
        cmd = exec.Command("shutdown", "/r", "/t", "0")
    } else {
        cmd = exec.Command("shutdown", "-r", "now")
    }

    err := cmd.Run()
    if err != nil {
        log.Fatal(err)
    }
}
335 chars
22 lines

In the above code, we first determine the operating system using the runtime.GOOS constant. Based on this, we create an appropriate exec.Cmd instance with required command and arguments. Finally, we call the Run method on the command instance to execute the command. If there is any error, we log the error message using the log.Fatal method.

gistlibby LogSnag