summaryrefslogtreecommitdiff
path: root/system/search/backup.go
blob: 9223636f586b7a4edd479adaa860f7f743ed4151 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package search

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"os"
	"path/filepath"
	"time"

	"github.com/ponzu-cms/ponzu/system/backup"
)

// Backup creates an archive of a project's search index and writes it
// to the response as a download
func Backup(ctx context.Context, res http.ResponseWriter) error {
	ts := time.Now().Unix()
	filename := fmt.Sprintf("search-%d.bak.tar.gz", ts)
	tmp := os.TempDir()
	bk := filepath.Join(tmp, filename)

	// create search-{stamp}.bak.tar.gz
	f, err := os.Create(bk)
	if err != nil {
		return err
	}

	backup.ArchiveFS(ctx, "search", f)

	err = f.Close()
	if err != nil {
		return err
	}

	// write data to response
	data, err := os.Open(bk)
	if err != nil {
		return err
	}
	defer data.Close()
	defer os.Remove(bk)

	disposition := `attachment; filename=%s`
	info, err := data.Stat()
	if err != nil {
		return err
	}

	res.Header().Set("Content-Type", "application/octet-stream")
	res.Header().Set("Content-Disposition", fmt.Sprintf(disposition, ts))
	res.Header().Set("Content-Length", fmt.Sprintf("%d", info.Size()))

	_, err = io.Copy(res, data)

	return err
}