-
Notifications
You must be signed in to change notification settings - Fork 1
/
upload.go
93 lines (80 loc) · 1.77 KB
/
upload.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package storage
import (
"context"
"fmt"
"io"
"os"
"path/filepath"
"time"
"github.com/briandowns/spinner"
"github.com/fatih/color"
)
//Size of maximum upload file
//i.e. upload object's size should not be more than 20MB.
const (
KB = 1 << 10
MB = 1 << 20
maxSize = 20 * MB
)
type uploadObject struct {
source string
destination string
bucketName string
}
func NewUploadObject(sourcePath, destinationPath, bucketName string) *uploadObject {
return &uploadObject{
source: sourcePath,
destination: destinationPath,
bucketName: bucketName,
}
}
func (u *uploadObject) UploadTarBallToGCS() error {
client, err := GetStorageClient()
if err != nil {
return err
}
writer := client.Bucket(u.bucketName).Object(u.destination).NewWriter(context.Background())
reader, err := os.Open(u.source)
defer reader.Close()
if err != nil {
return err
}
fileInfo, err := reader.Stat()
if err != nil {
return err
}
b := fileInfo.Size()
if b > maxSize {
_ = removeSourceFile(u.source)
return fmt.Errorf("You can't upload file which is more than 20MB,Your object size is %.2fMB", float64(b)/MB)
}
s := spinner.New(spinner.CharSets[11], 100*time.Millisecond)
s.Color("yellow", "bold")
s.Suffix = fmt.Sprintf(" Uploading: %.2f KB of source code file ", float64(b)/KB)
s.Start()
_, err = io.Copy(writer, reader)
if err != nil {
s.Stop()
return err
}
err = writer.Close()
if err != nil {
s.Stop()
_ = removeSourceFile(u.source)
return err
}
s.Stop()
fmt.Println(color.HiGreenString("Successfully uploaded %s file ✔︎", filepath.Base(u.source)))
err = removeSourceFile(u.source)
if err != nil {
return err
}
return nil
}
func removeSourceFile(path string) error {
err := os.Remove(path)
if err != nil {
return err
}
return nil
}