@@ -62,14 +62,32 @@ func (s FileSystem) Put(key string, img []byte) error {
6262 }
6363
6464 if _ , err := os .Stat (imgPath ); os .IsNotExist (err ) {
65- f , err := os .Create ( imgPath )
65+ f , err := os .CreateTemp ( dir , "tmpthumb" )
6666 if err != nil {
67- return errors .Wrapf (err , "could not create file \" %s\" " , key )
67+ return errors .Wrapf (err , "could not create temporary file for \" %s\" " , key )
6868 }
6969 defer f .Close ()
7070
71- if _ , err = f .Write (img ); err != nil {
72- return errors .Wrapf (err , "could not write to file \" %s\" " , key )
71+ // if there was a problem writing, remove the temporary file
72+ if _ , writeErr := f .Write (img ); writeErr != nil {
73+ if remErr := os .Remove (f .Name ()); remErr != nil {
74+ return errors .Wrapf (remErr , "could not cleanup temporary file for \" %s\" " , key )
75+ }
76+ return errors .Wrapf (writeErr , "could not write to temporary file for \" %s\" " , key )
77+ }
78+
79+ // if there wasn't a problem, ensure the data is written into disk
80+ if synErr := f .Sync (); synErr != nil {
81+ return errors .Wrapf (synErr , "could not sync temporary file data into the disk for \" %s\" " , key )
82+ }
83+
84+ // rename the temporary file to the final file
85+ if renErr := os .Rename (f .Name (), imgPath ); renErr != nil {
86+ // if we couldn't rename, remove the temporary file
87+ if remErr := os .Remove (f .Name ()); remErr != nil {
88+ return errors .Wrapf (remErr , "rename failed and could not cleanup temporary file for \" %s\" " , key )
89+ }
90+ return errors .Wrapf (renErr , "could not rename temporary file to \" %s\" " , key )
7391 }
7492 }
7593
0 commit comments