-
Notifications
You must be signed in to change notification settings - Fork 16
/
appstore.go
85 lines (71 loc) · 1.82 KB
/
appstore.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
package appstore
import (
"bytes"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"time"
"github.com/saucelabs/saucectl/internal/fileuploader"
)
// AppStore implements functions for AppStore interface
type AppStore struct {
HTTPClient *http.Client
URL string
Username string
AccessKey string
}
// New returns an implementation for AppStore
func New(url, username, accessKey string, timeout int) fileuploader.FileUploader {
return &AppStore{
HTTPClient: &http.Client{Timeout: time.Duration(timeout) * time.Second},
URL: url,
Username: username,
AccessKey: accessKey,
}
}
// Upload uploads file to remote storage
func (s *AppStore) Upload(fileName, formType string) error {
body, contentType, err := readFile(fileName, formType)
if err != nil {
return err
}
request, err := createRequest(s.URL, s.Username, s.AccessKey, body, contentType)
if err != nil {
return err
}
resp, err := s.HTTPClient.Do(request)
if err != nil {
return err
}
defer resp.Body.Close()
_, err = ioutil.ReadAll(resp.Body)
return err
}
func readFile(fileName, formType string) (*bytes.Buffer, string, error) {
file, err := os.Open(fileName)
if err != nil {
return nil, "", err
}
defer file.Close()
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
defer writer.Close()
part, err := writer.CreateFormFile(formType, filepath.Base(file.Name()))
if err != nil {
return nil, "", err
}
io.Copy(part, file)
return body, writer.FormDataContentType(), nil
}
func createRequest(url, username, accesskey string, body *bytes.Buffer, contentType string) (*http.Request, error) {
request, err := http.NewRequest(http.MethodPost, url, body)
if err != nil {
return nil, err
}
request.Header.Set("Content-Type", contentType)
request.SetBasicAuth(username, accesskey)
return request, nil
}