forked from ponzu-cms/ponzu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backup.go
37 lines (30 loc) · 830 Bytes
/
backup.go
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
package db
import (
"context"
"fmt"
"net/http"
"time"
"github.com/boltdb/bolt"
)
// Backup writes a snapshot of the system.db database to an HTTP response. The
// output is discarded if we get a cancellation signal.
func Backup(ctx context.Context, res http.ResponseWriter) error {
errChan := make(chan error, 1)
go func() {
errChan <- store.View(func(tx *bolt.Tx) error {
ts := time.Now().Unix()
disposition := `attachment; filename="system-%d.db.bak"`
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", int(tx.Size())))
_, err := tx.WriteTo(res)
return err
})
}()
select {
case <-ctx.Done():
return ctx.Err()
case err := <-errChan:
return err
}
}