Created
February 27, 2017 12:26
-
-
Save deadcheat/f83fe39801c16999e37538fa5ab24e8a to your computer and use it in GitHub Desktop.
ファイルの変更を検知してサーバーを再起動するサンプル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"time" | |
"net/http" | |
"github.com/radovskyb/watcher" | |
"golang.org/x/net/context" | |
) | |
func main() { | |
w := watcher.New() | |
srv := startServer("first time") | |
// starting file watch | |
i := 0 | |
go func() { | |
for { | |
select { | |
case event := <-w.Event: | |
fmt.Println(event) | |
if event.Op == watcher.Create { | |
fmt.Println("shutdown request") | |
ctx, _ := context.WithTimeout(context.Background(), 1*time.Second) | |
srv.Shutdown(ctx) | |
fmt.Println("restart request") | |
i = i + 1 | |
srv = startServer(fmt.Sprintf("second time later %d", i)) | |
} | |
case err := <-w.Error: | |
log.Fatalln(err) | |
case <-w.Closed: | |
return | |
} | |
} | |
}() | |
if err := w.Add("."); err != nil { | |
log.Fatalln(err) | |
} | |
// Print a list of all of the files and folders currently | |
// being watched and their paths. | |
for path, f := range w.WatchedFiles() { | |
fmt.Printf("%s: %s\n", path, f.Name()) | |
} | |
fmt.Println() | |
// Trigger 2 events after watcher started. | |
go func() { | |
w.Wait() | |
// w.TriggerEvent(watcher.Create, nil) | |
// w.TriggerEvent(watcher.Remove, nil) | |
}() | |
// Start the watching process - it'll check for changes every 100ms. | |
if err := w.Start(time.Millisecond * 100); err != nil { | |
log.Fatalln(err) | |
} | |
} | |
func createHandler(test string) http.Handler { | |
m := http.NewServeMux() | |
m.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { | |
fmt.Fprintf(w, test) | |
}) | |
return m | |
} | |
func startServer(test string) *http.Server { | |
s := http.Server{ | |
Addr: ":4000", | |
Handler: createHandler(test), | |
} | |
go func() { | |
if err := s.ListenAndServe(); err != nil { | |
log.Println("stopped", err) | |
} | |
}() | |
return &s | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment