write api file automically
Signed-off-by: Tiger <rbalajis25@gmail.com>
Tiger committed
May 6, 2020 at 22:42 UTC
17ec10436f22a63e4c0e05375df329428f7fa0a8
1 file changed
+12
-4
repo/fsrepo/fsrepo.go
+12
-4
@@ -359,14 +359,22 @@ func (r *FSRepo) Path() string {
359
360
// SetAPIAddr writes the API Addr to the /api file.
361
func (r *FSRepo) SetAPIAddr(addr ma.Multiaddr) error {
362
- f, err := os.Create(filepath.Join(r.path, apiFile))
362
+ // Create a temp file to write the address, so that we don't leave empty file when the
363
+ // program crashes after creating the file.
364
+ f, err := os.Create(filepath.Join(r.path, apiFile+"-tmp"))
365
if err != nil {
366
return err
367
}
366
- defer f.Close()
368
368
- _, err = f.WriteString(addr.String())
369
- return err
369
+ if _, err = f.WriteString(addr.String()); err != nil {
370
+ return err
371
+ }
372
+ if err = f.Close(); err != nil {
373
+ return err
374
+ }
375
+
376
+ // Atomically rename the temp file to the correct file name.
377
+ return os.Rename(filepath.Join(r.path, apiFile+"-tmp"), filepath.Join(r.path, apiFile))
378
}
379
380
// openConfig returns an error if the config file is not present.