/
plugin.go
103 lines (87 loc) · 2.05 KB
/
plugin.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
94
95
96
97
98
99
100
101
102
103
package sdk
import (
"bytes"
"fmt"
"io"
"mime/multipart"
"os"
"path"
"path/filepath"
)
//DownloadPlugin download plugin from action
func DownloadPlugin(name string, destdir string) error {
var lasterr error
for retry := 5; retry >= 0; retry-- {
uri := fmt.Sprintf("/plugin/download/%s", name)
reader, code, err := Stream("GET", uri, nil)
if err != nil {
lasterr = err
continue
}
if code >= 300 {
lasterr = fmt.Errorf("HTTP %d", code)
continue
}
destPath := path.Join(destdir, name)
//If the file already exists, remove it
if _, errstat := os.Stat(destPath); errstat == nil {
os.RemoveAll(destPath)
}
f, err := os.OpenFile(destPath, os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return err
}
if _, err = io.Copy(f, reader); err != nil {
lasterr = err
}
if err := f.Close(); err == nil {
fmt.Printf("Download %s completed\n", destPath)
return nil
}
}
return fmt.Errorf("x5: %s", lasterr)
}
//UploadPlugin uploads binary file to perform a new action
func UploadPlugin(filePath string, update bool) ([]byte, error) {
if _, err := os.Stat(filePath); os.IsNotExist(err) {
return nil, err
}
file, err := os.Open(filePath)
if err != nil {
return nil, err
}
defer file.Close()
//_, name := filepath.Split(filePath)
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile("UploadFile", filepath.Base(filePath))
if err != nil {
return nil, err
}
_, err = io.Copy(part, file)
err = writer.Close()
if err != nil {
return nil, err
}
method := "POST"
if update {
method = "PUT"
}
btes, code, err := UploadMultiPart(method, "/plugin", body, SetHeader("uploadfile", filePath), SetHeader("Content-Type", writer.FormDataContentType()))
if err != nil {
return nil, err
}
if code >= 300 {
return nil, fmt.Errorf("HTTP Error %d\n", code)
}
return btes, nil
}
//DeletePlugin delete plugin
func DeletePlugin(name string) error {
path := fmt.Sprintf("/plugin/%s", name)
_, _, err := Request("DELETE", path, nil)
if err != nil {
return err
}
return nil
}