From 36d8b394e171968f4ef563ee0e55a4c7213e4df0 Mon Sep 17 00:00:00 2001 From: Alexandre Blazart Date: Thu, 13 Sep 2018 21:18:56 +0200 Subject: [PATCH] Atomically write the json file --- mdns.go | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/mdns.go b/mdns.go index 6e60d8e..b52a241 100644 --- a/mdns.go +++ b/mdns.go @@ -14,6 +14,7 @@ package main import ( + "bytes" "context" "encoding/json" "flag" @@ -21,7 +22,6 @@ import ( "hash/fnv" "io/ioutil" "log" - "os" "sort" "strings" "sync" @@ -30,6 +30,7 @@ import ( "github.com/prometheus/common/model" "github.com/hashicorp/mdns" + "github.com/natefinch/atomic" ) type TargetGroup struct { @@ -102,12 +103,10 @@ func main() { if *output == "-" { fmt.Println(string(y)) } else { - file, err := os.Create(*output) // For read access. - if err != nil { + buf := bytes.NewBuffer(y) + if err := atomic.WriteFile(*output, buf); err != nil { log.Fatal(err) } - file.Write(y) - file.Close() } } }()