Skip to content

Instantly share code, notes, and snippets.

@NigelGreenway
Last active June 1, 2017 13:03
Show Gist options
  • Save NigelGreenway/a2817bd0b17a735fb3d044fa0cc6e865 to your computer and use it in GitHub Desktop.
Save NigelGreenway/a2817bd0b17a735fb3d044fa0cc6e865 to your computer and use it in GitHub Desktop.
File watcher for ReactPHP
# to run:
# ./react.go {path_to_server.php} ./dir_one ./dir_two ...
package main
import (
"log"
"os"
"os/exec"
"fmt"
"github.com/fsnotify/fsnotify"
)
func restartApp(serverPath string) {
fmt.Println("Restarting app")
cmd := fmt.Sprintf("ps aux|grep 'php %s'|head -n1|awk -d\"\\t\" '{ print $2}'", serverPath)
out, _ := exec.Command("sh", "-c", cmd).Output()
exec.Command("sh","-c", "kill " + string(out)).Output()
startApp(serverPath)
}
func systemWithoutOutput(cmd string, arg ...string) {
exec.Command(cmd, arg...).Start()
}
func startApp(pathToServer string) {
systemWithoutOutput("php", pathToServer)
}
func main() {
if len(os.Args) == 1 {
log.Fatal("A server file path is required!")
}
var (
serverPath = os.Args[1]
directoriesToWatch = os.Args[2:]
)
startApp(serverPath)
log.Println("Running React App")
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
defer watcher.Close()
done := make(chan bool)
go func() {
for {
select {
case event := <-watcher.Events:
if event.Op&fsnotify.Write == fsnotify.Write {
restartApp(serverPath)
}
case err := <-watcher.Errors:
log.Println("error:", err)
}
}
}()
for _, directory := range directoriesToWatch {
err = watcher.Add(directory)
if err != nil {
log.Fatal(err)
}
}
<-done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment