github.com/bosssauce/ponzu@v0.11.1-0.20200102001432-9bc41b703131/system/admin/upload/backup.go (about)

     1  package upload
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"io"
     7  	"net/http"
     8  	"os"
     9  	"path/filepath"
    10  	"time"
    11  
    12  	"github.com/ponzu-cms/ponzu/system/backup"
    13  )
    14  
    15  // Backup creates an archive of a project's uploads and writes it
    16  // to the response as a download
    17  func Backup(ctx context.Context, res http.ResponseWriter) error {
    18  	ts := time.Now().Unix()
    19  	filename := fmt.Sprintf("uploads-%d.bak.tar.gz", ts)
    20  	tmp := os.TempDir()
    21  	bk := filepath.Join(tmp, filename)
    22  
    23  	// create uploads-{stamp}.bak.tar.gz
    24  	f, err := os.Create(bk)
    25  	if err != nil {
    26  		return err
    27  	}
    28  
    29  	err = backup.ArchiveFS(ctx, "uploads", f)
    30  	if err != nil {
    31  		return err
    32  	}
    33  
    34  	err = f.Close()
    35  	if err != nil {
    36  		return err
    37  	}
    38  
    39  	// write data to response
    40  	data, err := os.Open(bk)
    41  	if err != nil {
    42  		return err
    43  	}
    44  	defer data.Close()
    45  	defer os.Remove(bk)
    46  
    47  	disposition := `attachment; filename=%s`
    48  	info, err := data.Stat()
    49  	if err != nil {
    50  		return err
    51  	}
    52  
    53  	res.Header().Set("Content-Type", "application/octet-stream")
    54  	res.Header().Set("Content-Disposition", fmt.Sprintf(disposition, ts))
    55  	res.Header().Set("Content-Length", fmt.Sprintf("%d", info.Size()))
    56  
    57  	_, err = io.Copy(res, data)
    58  
    59  	return err
    60  }