2015-05-05 01:04:17 +08:00
|
|
|
package setup
|
|
|
|
|
|
|
|
import (
|
|
|
|
"os"
|
|
|
|
"os/exec"
|
2015-05-06 01:08:45 +08:00
|
|
|
"strings"
|
2015-05-05 01:04:17 +08:00
|
|
|
|
|
|
|
"github.com/mholt/caddy/middleware"
|
|
|
|
)
|
|
|
|
|
|
|
|
func Startup(c *Controller) (middleware.Middleware, error) {
|
|
|
|
return nil, registerCallback(c, &c.Startup)
|
|
|
|
}
|
|
|
|
|
|
|
|
func Shutdown(c *Controller) (middleware.Middleware, error) {
|
|
|
|
return nil, registerCallback(c, &c.Shutdown)
|
|
|
|
}
|
|
|
|
|
|
|
|
// registerCallback registers a callback function to execute by
|
|
|
|
// using c to parse the line. It appends the callback function
|
|
|
|
// to the list of callback functions passed in by reference.
|
|
|
|
func registerCallback(c *Controller, list *[]func() error) error {
|
|
|
|
for c.Next() {
|
2015-05-06 01:08:45 +08:00
|
|
|
args := c.RemainingArgs()
|
|
|
|
if len(args) == 0 {
|
2015-05-05 01:04:17 +08:00
|
|
|
return c.ArgErr()
|
|
|
|
}
|
|
|
|
|
2015-05-06 01:08:45 +08:00
|
|
|
nonblock := false
|
|
|
|
if len(args) > 1 && args[len(args)-1] == "&" {
|
|
|
|
// Run command in background; non-blocking
|
|
|
|
nonblock = true
|
|
|
|
args = args[:len(args)-1]
|
|
|
|
}
|
|
|
|
|
|
|
|
command, args, err := middleware.SplitCommandAndArgs(strings.Join(args, " "))
|
2015-05-05 01:04:17 +08:00
|
|
|
if err != nil {
|
|
|
|
return c.Err(err.Error())
|
|
|
|
}
|
|
|
|
|
|
|
|
fn := func() error {
|
|
|
|
cmd := exec.Command(command, args...)
|
2015-05-06 01:20:57 +08:00
|
|
|
cmd.Stdin = os.Stdin
|
2015-05-05 01:04:17 +08:00
|
|
|
cmd.Stdout = os.Stdout
|
|
|
|
cmd.Stderr = os.Stderr
|
2015-05-06 01:08:45 +08:00
|
|
|
|
|
|
|
if nonblock {
|
|
|
|
return cmd.Start()
|
|
|
|
} else {
|
|
|
|
return cmd.Run()
|
|
|
|
}
|
2015-05-05 01:04:17 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
*list = append(*list, fn)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|