Skip to content

Commit

Permalink
Properly handle closing of files after writing (#113)
Browse files Browse the repository at this point in the history
  • Loading branch information
samcoe committed Mar 20, 2023
1 parent 9013119 commit 32d3260
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 20 deletions.
26 changes: 16 additions & 10 deletions internal/api/cache.go
Expand Up @@ -170,33 +170,39 @@ func (fs *fileStorage) read(key string) (*http.Response, error) {
return res, err
}

func (fs *fileStorage) store(key string, res *http.Response) error {
func (fs *fileStorage) store(key string, res *http.Response) (storeErr error) {
cacheFile := fs.filePath(key)

fs.mu.Lock()
defer fs.mu.Unlock()

err := os.MkdirAll(filepath.Dir(cacheFile), 0755)
if err != nil {
return err
if storeErr = os.MkdirAll(filepath.Dir(cacheFile), 0755); storeErr != nil {
return
}

f, err := os.OpenFile(cacheFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
var f *os.File
if f, storeErr = os.OpenFile(cacheFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600); storeErr != nil {
return
}
defer f.Close()

defer func() {
if err := f.Close(); storeErr == nil && err != nil {
storeErr = err
}
}()

var origBody io.ReadCloser
if res.Body != nil {
origBody, res.Body = copyStream(res.Body)
defer res.Body.Close()
}
err = res.Write(f)

storeErr = res.Write(f)
if origBody != nil {
res.Body = origBody
}
return err

return
}

func copyStream(r io.ReadCloser) (io.ReadCloser, io.ReadCloser) {
Expand Down
23 changes: 13 additions & 10 deletions pkg/config/config.go
Expand Up @@ -281,18 +281,21 @@ func readFile(filename string) ([]byte, error) {
return data, nil
}

func writeFile(filename string, data []byte) error {
err := os.MkdirAll(filepath.Dir(filename), 0771)
if err != nil {
return err
func writeFile(filename string, data []byte) (writeErr error) {
if writeErr = os.MkdirAll(filepath.Dir(filename), 0771); writeErr != nil {
return
}
file, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
var file *os.File
if file, writeErr = os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600); writeErr != nil {
return
}
defer file.Close()
_, err = file.Write(data)
return err
defer func() {
if err := file.Close(); writeErr == nil && err != nil {
writeErr = err
}
}()
_, writeErr = file.Write(data)
return
}

var defaultGeneralEntries = `
Expand Down

0 comments on commit 32d3260

Please sign in to comment.