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

     1  package analytics
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"net/http"
     7  	"time"
     8  
     9  	"github.com/boltdb/bolt"
    10  )
    11  
    12  // Backup writes a snapshot of the system.db database to an HTTP response. The
    13  // output is discarded if we get a cancellation signal.
    14  func Backup(ctx context.Context, res http.ResponseWriter) error {
    15  	errChan := make(chan error, 1)
    16  
    17  	go func() {
    18  		errChan <- store.View(func(tx *bolt.Tx) error {
    19  			ts := time.Now().Unix()
    20  			disposition := `attachment; filename="analytics-%d.db.bak"`
    21  
    22  			res.Header().Set("Content-Type", "application/octet-stream")
    23  			res.Header().Set("Content-Disposition", fmt.Sprintf(disposition, ts))
    24  			res.Header().Set("Content-Length", fmt.Sprintf("%d", int(tx.Size())))
    25  
    26  			_, err := tx.WriteTo(res)
    27  			return err
    28  		})
    29  	}()
    30  
    31  	select {
    32  	case <-ctx.Done():
    33  		return ctx.Err()
    34  	case err := <-errChan:
    35  		return err
    36  	}
    37  }