systemaction.go 709 B

1234567891011121314151617181920212223242526272829303132
  1. package systemaction
  2. import (
  3. "fmt"
  4. "os/exec"
  5. "strings"
  6. )
  7. type Service struct{}
  8. func New() *Service { return &Service{} }
  9. func (s *Service) Reboot() error {
  10. return runCommand("systemctl", "reboot")
  11. }
  12. func (s *Service) Shutdown() error {
  13. return runCommand("systemctl", "poweroff")
  14. }
  15. func runCommand(name string, args ...string) error {
  16. cmd := exec.Command(name, args...)
  17. output, err := cmd.CombinedOutput()
  18. if err != nil {
  19. trimmed := strings.TrimSpace(string(output))
  20. if trimmed == "" {
  21. return fmt.Errorf("%s failed", strings.Join(append([]string{name}, args...), " "))
  22. }
  23. return fmt.Errorf("%s failed: %s", strings.Join(append([]string{name}, args...), " "), trimmed)
  24. }
  25. return nil
  26. }