hook.go 885 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package hook
  2. import (
  3. "log"
  4. "os"
  5. "os/exec"
  6. "strings"
  7. "github.com/mholt/caddy"
  8. )
  9. // Hook executes a command.
  10. func (cfg *Config) Hook(event caddy.EventName, info interface{}) error {
  11. if event != cfg.Event {
  12. return nil
  13. }
  14. nonblock := false
  15. if len(cfg.Args) >= 1 && cfg.Args[len(cfg.Args)-1] == "&" {
  16. // Run command in background; non-blocking
  17. nonblock = true
  18. cfg.Args = cfg.Args[:len(cfg.Args)-1]
  19. }
  20. // Execute command.
  21. cmd := exec.Command(cfg.Command, cfg.Args...)
  22. cmd.Stdin = os.Stdin
  23. cmd.Stdout = os.Stdout
  24. cmd.Stderr = os.Stderr
  25. if nonblock {
  26. log.Printf("[INFO] Nonblocking Command \"%s %s\" with ID %s", cfg.Command, strings.Join(cfg.Args, " "), cfg.ID)
  27. return cmd.Start()
  28. }
  29. log.Printf("[INFO] Blocking Command \"%s %s\" with ID %s", cfg.Command, strings.Join(cfg.Args, " "), cfg.ID)
  30. err := cmd.Run()
  31. if err != nil {
  32. return err
  33. }
  34. return nil
  35. }