func UnixAudienceListener(sockaddr string) { fi, err := os.Stat(sockaddr) if err == nil { fmode := fi.Mode() if fmode&os.ModeType == os.ModeSocket { o.Warn("Removing stale socket at %s", sockaddr) os.Remove(sockaddr) } else { o.Fail("%s exists and is not a socket", sockaddr) } } laddr, err := net.ResolveUnixAddr("unix", sockaddr) o.MightFail(err, "Couldn't resolve audience socket address") l, err := net.ListenUnix("unix", laddr) o.MightFail(err, "Couldn't start audience unixsock listener") // Fudge the permissions on the unixsock! fi, err = os.Stat(sockaddr) if err == nil { os.Chmod(sockaddr, fi.Mode()|0777) } else { o.Warn("Couldn't fudge permission on audience socket: %s", err) } // make sure we clean up the unix socket when we die. defer l.Close() defer os.Remove(sockaddr) AudienceListener(l) }
// RemoveSnapServices disables and removes service units for the applications from the snap which are services. func RemoveSnapServices(s *snap.Info, inter interacter) error { sysd := systemd.New(dirs.GlobalRootDir, inter) nservices := 0 for _, app := range s.Apps { if app.Daemon == "" { continue } nservices++ serviceName := filepath.Base(app.ServiceFile()) if err := sysd.Disable(serviceName); err != nil { return err } if err := os.Remove(app.ServiceFile()); err != nil && !os.IsNotExist(err) { logger.Noticef("Failed to remove service file for %q: %v", serviceName, err) } if err := os.Remove(app.ServiceSocketFile()); err != nil && !os.IsNotExist(err) { logger.Noticef("Failed to remove socket file for %q: %v", serviceName, err) } } // only reload if we actually had services if nservices > 0 { if err := sysd.DaemonReload(); err != nil { return err } } return nil }
func (this *MemeOCR) Run(image string) (*OCRResult, error) { imageTif := fmt.Sprintf("%s_meme.jpg", image) outText := fmt.Sprintf("%s_meme", image) preprocessingArgs := []string{image, "-resize", "400%", "-fill", "black", "-fuzz", "10%", "+opaque", "#FFFFFF", imageTif} tesseractArgs := []string{"-l", "meme", imageTif, outText} err := runProcessorCommand(GetExecPath(), preprocessingArgs) if err != nil { return nil, errors.New(fmt.Sprintf("Meme preprocessing command failed with error = %v", err)) } defer os.Remove(imageTif) err = runProcessorCommand("tesseract", tesseractArgs) if err != nil { return nil, errors.New(fmt.Sprintf("Meme tesseract command failed with error = %v", err)) } defer os.Remove(outText + ".txt") text, err := ioutil.ReadFile(outText + ".txt") if err != nil { return nil, err } result := strings.ToLower(strings.TrimSpace(string(text[:]))) return newOCRResult(this.name, result), nil }
func makeDiskImage() error { log.Printf("Creating %s MB hard disk image...", B2D.DISKSIZE) vbm("createhd", "--format", "VMDK", "--filename", B2D.DISK, "--size", B2D.DISKSIZE) // We do the following so boot2docker vm will auto-format the disk for us // upon first boot. const tmp_flag_file = "format-flag.txt" const tmp_vmdk_file = "format-flag.vmdk" f, err := os.Create(tmp_flag_file) if err != nil { return err } err = f.Truncate(5 * 1024 * 1024) // 5MB if err != nil { return err } _, err = f.WriteString("boot2docker, please format-me\n") if err != nil { return err } err = f.Close() if err != nil { return err } vbm("convertfromraw", tmp_flag_file, tmp_vmdk_file, "--format", "VMDK") vbm("clonehd", tmp_vmdk_file, B2D.DISK, "--existing") vbm("closemedium", "disk", tmp_vmdk_file) os.Remove(tmp_flag_file) os.Remove(tmp_vmdk_file) return nil }
// Reading a symlink to a file must fail func TestReadSymlinkedDirectoryToFile(t *testing.T) { var err error var file *os.File if file, err = os.Create("/tmp/testReadSymlinkToFile"); err != nil { t.Fatalf("failed to create file: %s", err) } file.Close() if err = os.Symlink("/tmp/testReadSymlinkToFile", "/tmp/fileLinkTest"); err != nil { t.Errorf("failed to create symlink: %s", err) } var path string if path, err = ReadSymlinkedDirectory("/tmp/fileLinkTest"); err == nil { t.Fatalf("ReadSymlinkedDirectory on a symlink to a file should've failed") } if path != "" { t.Fatalf("path should've been empty: %s", path) } if err = os.Remove("/tmp/testReadSymlinkToFile"); err != nil { t.Errorf("failed to remove file: %s", err) } if err = os.Remove("/tmp/fileLinkTest"); err != nil { t.Errorf("failed to remove symlink: %s", err) } }
func TestInsertRead(t *testing.T) { tmp := "/tmp/tiedot_test_col" os.Remove(tmp) defer os.Remove(tmp) col, err := OpenCollection(tmp) if err != nil { t.Fatalf("Failed to open: %v", err) return } defer col.Close() docs := [][]byte{ []byte("abc"), []byte("1234")} ids := [2]int{} if ids[0], err = col.Insert(docs[0]); ids[0] != 0 || err != nil { t.Fatalf("Failed to insert: %d %v", ids[0], err) } if ids[1], err = col.Insert(docs[1]); err != nil { t.Fatalf("Failed to insert: %v", err) } if doc0 := col.Read(ids[0]); doc0 == nil || strings.TrimSpace(string(doc0)) != string(docs[0]) { t.Fatal("Failed to read", doc0) } if doc1 := col.Read(ids[1]); doc1 == nil || strings.TrimSpace(string(doc1)) != string(docs[1]) { t.Fatalf("Failed to read") } // it shall not panic col.Read(col.Size) }
func (m *migrateCmd) run(e *parsecli.Env) error { c, err := parsecli.ConfigFromDir(e.Root) if err != nil { return err } c, err = m.upgradeLegacy(e, c) if err != nil { return err } localErr := parsecli.StoreConfig(e, c) projectErr := parsecli.StoreProjectConfig(e, c) if localErr == nil && projectErr == nil { legacy := filepath.Join(e.Root, parsecli.LegacyConfigFile) err := os.Remove(legacy) if err != nil { fmt.Fprintf(e.Err, "Could not delete: %q. Please remove this file manually.\n", legacy) } } else { local := filepath.Join(e.Root, parsecli.ParseLocal) err := os.Remove(local) if err != nil { fmt.Fprintf(e.Err, "Failed to clean up: %q. Please remove this file manually.\n", local) } project := filepath.Join(e.Root, parsecli.ParseProject) err = os.Remove(project) if err != nil { fmt.Fprintf(e.Err, "Failed to clean up: %q. Please remove this file manually.\n", project) } } fmt.Fprintln(e.Out, "Successfully migrated to the preferred config format.") return nil }
func TestVerify(t *testing.T) { o := &Options{noClone: true} db, err := CreateTemp("", "temp", ".db", o) if err != nil { t.Fatal(err) } defer func() { name := db.Name() err := db.Close() if err := os.Remove(name); err != nil { t.Error(err) } if err := os.Remove(o._WAL); err != nil { t.Error(err) } if err != nil { t.Error(err) } }() t.Log(db.Name(), o._WAL) if err := db.Verify(nil, nil); err != nil { t.Error(err) } }
func TestCreate(t *testing.T) { const name = "_testdata/tempname" os.Remove(name) o := &Options{noClone: true} db, err := Create(name, o) if err != nil { t.Fatal(err) } defer func() { err := db.Close() if err := os.Remove(name); err != nil { t.Error(err) } if err := os.Remove(o._WAL); err != nil { t.Error(err) } if err != nil { t.Error(err) } }() if _, err = Create(name, &Options{noClone: true}); err == nil { t.Error("unexpected success") return } if _, err = Open(name, &Options{noClone: true}); err == nil { t.Error("unexpected success") return } }
func (f *fileStorageWriter) Put(name string, r io.Reader, length int64) error { if isInternalPath(name) { return &os.PathError{ Op: "Put", Path: name, Err: os.ErrPermission, } } fullpath := f.fullPath(name) dir := filepath.Dir(fullpath) if err := os.MkdirAll(dir, 0755); err != nil { return err } tmpdir := filepath.Join(f.path, ".tmp") if err := os.MkdirAll(tmpdir, 0755); err != nil { return err } defer os.Remove(tmpdir) // Write to a temporary file first, and then move (atomically). file, err := ioutil.TempFile(tmpdir, "juju-filestorage-") if err != nil { return err } _, err = io.CopyN(file, r, length) file.Close() if err != nil { os.Remove(file.Name()) return err } return utils.ReplaceFile(file.Name(), fullpath) }
func TestWALName(t *testing.T) { db, err := CreateTemp("", "kv-wal-name", ".test", &Options{noClone: true}) if err != nil { t.Fatal(err) } defer func(n, wn string) { if _, err := os.Stat(n); err != nil { t.Error(err) } else { if err := os.Remove(n); err != nil { t.Error(err) } } if _, err := os.Stat(wn); err != nil { t.Error(err) } else { if err := os.Remove(wn); err != nil { t.Error(err) } } t.Logf("%q\n%q", n, wn) }(db.Name(), db.WALName()) if err := db.Close(); err != nil { t.Error(err) return } if n := db.WALName(); n != "" { t.Error(n) } }
func (eogHandler) Display(ctx *context.T, mimetype string, r io.ReadCloser) (func(), error) { // eog cannot read from a pipe, so we have to write the file to // the filesystem before displaying it. defer r.Close() tmp, err := ioutil.TempFile("", "") if err != nil { return nil, err } if _, err := io.Copy(tmp, r); err != nil { os.Remove(tmp.Name()) return nil, err } tmp.Close() cmd := exec.Command("eog", "--display", ":0", "-f", tmp.Name()) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr stop := func() { if err := cmd.Process.Kill(); err != nil { vlog.Errorf("Could not kill eog: %v", err) } cmd.Wait() os.Remove(tmp.Name()) } if err := cmd.Start(); err != nil { return stop, err } return stop, nil }
func (omxHandler) Display(ctx *context.T, mimetype string, r io.ReadCloser) (func(), error) { defer r.Close() tmp, err := ioutil.TempFile("", "") if err != nil { return nil, err } if _, err := io.Copy(tmp, r); err != nil { os.Remove(tmp.Name()) return nil, err } tmp.Close() args := []string{ "-b", tmp.Name(), } vlog.Infof("Running: omxplayer %s", strings.Join(args, " ")) cmd := exec.Command("omxplayer", args...) cmd.Stdin = r cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Start(); err != nil { return nil, err } return func() { if err := cmd.Process.Kill(); err != nil { vlog.Errorf("Could not kill omx: %v", err) } cmd.Wait() os.Remove(tmp.Name()) }, nil }
func TestSystem(t *testing.T) { tmpdir, err := ioutil.TempDir("", "") require.NoError(t, err) defer os.RemoveAll(tmpdir) sys := NewSystem(SystemConfig{BuildTempDir: tmpdir}) { tmpFile1, err := sys.SmallTempFile() if assert.NoError(t, err) { defer os.Remove(tmpFile1.Name()) defer tmpFile1.Close() tmpFile2, err := sys.SmallTempFile() if assert.NoError(t, err) { defer os.Remove(tmpFile2.Name()) defer tmpFile2.Close() assert.NotEqual(t, tmpFile1.Name(), tmpFile2.Name()) } } } { tmpDir1, err := sys.TempDirForBuild() if assert.NoError(t, err) { assert.True(t, strings.HasPrefix(tmpDir1, tmpdir)) tmpDir2, err := sys.TempDirForBuild() if assert.NoError(t, err) { assert.True(t, strings.HasPrefix(tmpDir2, tmpdir)) assert.NotEqual(t, tmpDir1, tmpDir2) } } } }
func TestCanonicalCircular(t *testing.T) { tmp1, err := tmpfile("circular") if err != nil { t.Fatal(err) } tmp2, err := tmpfile("circular") if err != nil { t.Fatal(nonil(err, os.Remove(tmp1))) } defer removeall(tmp1, tmp2) // Symlink tmp1 -> tmp2. if err = nonil(os.Remove(tmp1), os.Symlink(tmp2, tmp1)); err != nil { t.Fatal(err) } // Symlnik tmp2 -> tmp1. if err = nonil(os.Remove(tmp2), os.Symlink(tmp1, tmp2)); err != nil { t.Fatal(err) } if _, err = canonical(tmp1); err == nil { t.Fatalf("want canonical(%q)!=nil", tmp1) } if _, ok := err.(*os.PathError); !ok { t.Fatalf("want canonical(%q)=os.PathError; got %T", tmp1, err) } }
func BenchmarkFirst16(b *testing.B) { const n = 5000 g := runtime.GOMAXPROCS(0) defer runtime.GOMAXPROCS(g) o := &Options{noClone: true} db, err := CreateTemp("_testdata", "temp", ".db", o) if err != nil { b.Fatal(err) } dbname := db.Name() defer func(n string) { db.Close() os.Remove(n) os.Remove(o._WAL) }(dbname) rng := fc() for i := 0; i < n; i++ { if err := db.Set(n2b(rng.Next()), n2b(rng.Next())); err != nil { b.Fatal(err) } } b.ResetTimer() for i := 0; i < b.N; i++ { db.First() } b.StopTimer() }
func TestConflictingCurrentContext(t *testing.T) { commandLineFile, _ := ioutil.TempFile("", "") defer os.Remove(commandLineFile.Name()) envVarFile, _ := ioutil.TempFile("", "") defer os.Remove(envVarFile.Name()) mockCommandLineConfig := clientcmdapi.Config{ CurrentContext: "any-context-value", } mockEnvVarConfig := clientcmdapi.Config{ CurrentContext: "a-different-context", } WriteToFile(mockCommandLineConfig, commandLineFile.Name()) WriteToFile(mockEnvVarConfig, envVarFile.Name()) loadingRules := ClientConfigLoadingRules{ CommandLinePath: commandLineFile.Name(), EnvVarPath: envVarFile.Name(), } mergedConfig, err := loadingRules.Load() if err != nil { t.Errorf("Unexpected error: %v", err) } if mergedConfig.CurrentContext != mockCommandLineConfig.CurrentContext { t.Errorf("expected %v, got %v", mockCommandLineConfig.CurrentContext, mergedConfig.CurrentContext) } }
func startIpc(cfg IpcConfig, codec codec.Codec, api shared.EthereumApi) error { os.Remove(cfg.Endpoint) // in case it still exists from a previous run l, err := net.Listen("unix", cfg.Endpoint) if err != nil { return err } l = fdtrack.WrapListener("ipc", l) os.Chmod(cfg.Endpoint, 0600) go func() { for { conn, err := l.Accept() if err != nil { glog.V(logger.Error).Infof("Error accepting ipc connection - %v\n", err) continue } id := newIpcConnId() glog.V(logger.Debug).Infof("New IPC connection with id %06d started\n", id) go handle(id, conn, api, codec) } os.Remove(cfg.Endpoint) }() glog.V(logger.Info).Infof("IPC service started (%s)\n", cfg.Endpoint) return nil }
// TestHostKeyCheckerInteraction tests to check nonexisting key func TestHostKeyCheckerInteraction(t *testing.T) { os.Remove(hostFileBackup) defer os.Remove(hostFileBackup) keyFile := NewHostKeyFile(hostFileBackup) checker := NewHostKeyChecker(keyFile) addr, key, _ := parseKnownHostsLine([]byte(hostLine)) tcpAddr, _ := net.ResolveTCPAddr("tcp", addr) // Refuse to add new host key checker.trustHost = trustHostNever if err := checker.Check("localhost", tcpAddr, key); err != ErrUntrustHost { t.Fatalf("checker should fail to put %v, %v in known_hosts", addr, tcpAddr.String()) } // Accept to add new host key checker.trustHost = trustHostAlways if err := checker.Check("localhost", tcpAddr, key); err != nil { t.Fatalf("checker should succeed to put %v, %v in known_hosts", addr, tcpAddr.String()) } // Use authorized key that have been added checker.trustHost = trustHostNever if err := checker.Check("localhost", tcpAddr, key); err != nil { t.Fatalf("checker should succeed to put %v, %v in known_hosts", addr, tcpAddr.String()) } }
func TestSeqpacketConnServer(t *testing.T) { if runtime.GOOS != "linux" { t.Skipf("skipping test on %q", runtime.GOOS) } for _, tt := range seqpacketConnServerTests { listening := make(chan string) done := make(chan int) switch tt.net { case "unixpacket": os.Remove(tt.saddr) os.Remove(tt.caddr) } go runStreamConnServer(t, tt.net, tt.saddr, listening, done) taddr := <-listening // wait for server to start runStreamConnClient(t, tt.net, taddr, tt.empty) <-done // make sure server stopped switch tt.net { case "unixpacket": os.Remove(tt.saddr) os.Remove(tt.caddr) } } }
func (s *SnapPart) remove(inter interacter) (err error) { // TODO[JRL]: check the logic here. I'm not sure “remove // everything if active, and the click hooks if not” makes // sense. E.g. are we removing fmk bins on fmk upgrade? Etc. if err := removeClickHooks(s.m, s.origin, false); err != nil { return err } if err := s.deactivate(false, inter); err != nil && err != ErrSnapNotActive { return err } err = os.RemoveAll(s.basedir) if err != nil { return err } // best effort(?) os.Remove(filepath.Dir(s.basedir)) // don't fail if icon can't be removed if helpers.FileExists(iconPath(s)) { if err := os.Remove(iconPath(s)); err != nil { logger.Noticef("Failed to remove store icon %s: %s", iconPath(s), err) } } return nil }
func (s *rootfsFilesystemSource) createFilesystem(params storage.FilesystemParams) (storage.Filesystem, error) { var filesystem storage.Filesystem if err := s.ValidateFilesystemParams(params); err != nil { return filesystem, errors.Trace(err) } path := filepath.Join(s.storageDir, params.Tag.Id()) if err := ensureDir(s.dirFuncs, path); err != nil { return filesystem, errors.Trace(err) } if err := ensureEmptyDir(s.dirFuncs, path); err != nil { return filesystem, errors.Trace(err) } sizeInMiB, err := s.dirFuncs.calculateSize(s.storageDir) if err != nil { os.Remove(path) return filesystem, errors.Annotate(err, "getting size") } if sizeInMiB < params.Size { os.Remove(path) return filesystem, errors.Errorf("filesystem is not big enough (%dM < %dM)", sizeInMiB, params.Size) } filesystem = storage.Filesystem{ params.Tag, names.VolumeTag{}, storage.FilesystemInfo{ FilesystemId: params.Tag.Id(), Size: sizeInMiB, }, } return filesystem, nil }
// Reading a symlink to a directory must return the directory func TestReadSymlinkedDirectoryExistingDirectory(t *testing.T) { var err error if err = os.Mkdir("/tmp/testReadSymlinkToExistingDirectory", 0777); err != nil { t.Errorf("failed to create directory: %s", err) } if err = os.Symlink("/tmp/testReadSymlinkToExistingDirectory", "/tmp/dirLinkTest"); err != nil { t.Errorf("failed to create symlink: %s", err) } var path string if path, err = ReadSymlinkedDirectory("/tmp/dirLinkTest"); err != nil { t.Fatalf("failed to read symlink to directory: %s", err) } if path != "/tmp/testReadSymlinkToExistingDirectory" { t.Fatalf("symlink returned unexpected directory: %s", path) } if err = os.Remove("/tmp/testReadSymlinkToExistingDirectory"); err != nil { t.Errorf("failed to remove temporary directory: %s", err) } if err = os.Remove("/tmp/dirLinkTest"); err != nil { t.Errorf("failed to remove symlink: %s", err) } }
func diff(b1, b2 []byte) (data []byte, err error) { f1, err := ioutil.TempFile("", "gofmt") if err != nil { return } defer os.Remove(f1.Name()) defer f1.Close() f2, err := ioutil.TempFile("", "gofmt") if err != nil { return } defer os.Remove(f2.Name()) defer f2.Close() f1.Write(b1) f2.Write(b2) data, err = exec.Command("diff", "-u", f1.Name(), f2.Name()).CombinedOutput() if len(data) > 0 { // diff exits with a non-zero status when the files don't match. // Ignore that failure as long as we get output. err = nil } return }
func (c *fileCmd) edit(config *lxd.Config, args []string) error { if len(args) != 1 { return errArgs } // If stdin isn't a terminal, read text from it if !terminal.IsTerminal(int(syscall.Stdin)) { return c.push(config, append([]string{os.Stdin.Name()}, args[0])) } // Create temp file f, err := ioutil.TempFile("", "lxd_file_edit_") fname := f.Name() f.Close() os.Remove(fname) defer os.Remove(fname) // Extract current value err = c.pull(config, append([]string{args[0]}, fname)) if err != nil { return err } _, err = shared.TextEditor(fname, []byte{}) if err != nil { return err } err = c.push(config, append([]string{fname}, args[0])) if err != nil { return err } return nil }
// UnmountPath is a common unmount routine that unmounts the given path and // deletes the remaining directory if successful. func UnmountPath(mountPath string, mounter mount.Interface) error { if pathExists, pathErr := PathExists(mountPath); pathErr != nil { return fmt.Errorf("Error checking if path exists: %v", pathErr) } else if !pathExists { glog.Warningf("Warning: Unmount skipped because path does not exist: %v", mountPath) return nil } notMnt, err := mounter.IsLikelyNotMountPoint(mountPath) if err != nil { return err } if notMnt { glog.Warningf("Warning: %q is not a mountpoint, deleting", mountPath) return os.Remove(mountPath) } // Unmount the mount path if err := mounter.Unmount(mountPath); err != nil { return err } notMnt, mntErr := mounter.IsLikelyNotMountPoint(mountPath) if mntErr != nil { return err } if notMnt { glog.V(4).Info("%q is unmounted, deleting the directory", mountPath) return os.Remove(mountPath) } return nil }
func (this *StandardOCR) Run(image string) (*OCRResult, error) { imageTif := fmt.Sprintf("%s_standard.jpg", image) outText := fmt.Sprintf("%s_standard", image) preprocessingArgs := []string{image, "-resize", "400%", "-type", "Grayscale", imageTif} tesseractArgs := []string{"-l", "eng", imageTif, outText} err := runProcessorCommand(GetExecPath(), preprocessingArgs) if err != nil { return nil, errors.New(fmt.Sprintf("Standard preprocessing command failed with error = %v", err)) } defer os.Remove(imageTif) err = runProcessorCommand("tesseract", tesseractArgs) if err != nil { return nil, errors.New(fmt.Sprintf("Standard tesseract command failed with error = %v", err)) } defer os.Remove(outText + ".txt") text, err := ioutil.ReadFile(outText + ".txt") if err != nil { return nil, err } result := strings.ToLower(strings.TrimSpace(string(text[:]))) return newOCRResult(this.name, result), nil }
// Flush flushes the index entry to the target file. func (ix *IndexWriter) Flush() { ix.addName("") var off [5]uint32 ix.main.writeString(magic) off[0] = ix.main.offset() for _, p := range ix.paths { ix.main.writeString(p) ix.main.writeString("\x00") } ix.main.writeString("\x00") off[1] = ix.main.offset() copyFile(ix.main, ix.nameData) off[2] = ix.main.offset() ix.mergePost(ix.main) off[3] = ix.main.offset() copyFile(ix.main, ix.nameIndex) off[4] = ix.main.offset() copyFile(ix.main, ix.postIndex) for _, v := range off { ix.main.writeUint32(v) } ix.main.writeString(trailerMagic) os.Remove(ix.nameData.name) for _, f := range ix.postFile { os.Remove(f.Name()) } os.Remove(ix.nameIndex.name) os.Remove(ix.postIndex.name) log.Printf("%d data bytes, %d index bytes", ix.totalBytes, ix.main.offset()) ix.main.flush() }
func (c *nfsCleaner) TearDownAt(dir string) error { mountpoint, err := c.mounter.IsMountPoint(dir) if err != nil { glog.Errorf("Error checking IsMountPoint: %v", err) return err } if !mountpoint { return os.Remove(dir) } if err := c.mounter.Unmount(dir); err != nil { glog.Errorf("Unmounting failed: %v", err) return err } mountpoint, mntErr := c.mounter.IsMountPoint(dir) if mntErr != nil { glog.Errorf("IsMountpoint check failed: %v", mntErr) return mntErr } if !mountpoint { if err := os.Remove(dir); err != nil { return err } } return nil }
func (cache *fFprobeCache) save(path string) error { cache.Lock() items := cache.c.Items() cache.Unlock() f, err := ioutil.TempFile(filepath.Dir(path), filepath.Base(path)) if err != nil { return err } enc := json.NewEncoder(f) err = enc.Encode(items) f.Close() if err != nil { os.Remove(f.Name()) return err } if runtime.GOOS == "windows" { err = os.Remove(path) if err == os.ErrNotExist { err = nil } } if err == nil { err = os.Rename(f.Name(), path) } if err == nil { log.Printf("saved cache with %d items", len(items)) } else { os.Remove(f.Name()) } return err }