-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
228 lines (180 loc) · 4.42 KB
/
main.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
package main
import (
"bytes"
"encoding/json"
"fmt"
//"io"
"io"
"io/ioutil"
"log"
"mime/multipart"
"net/http"
"net/url"
"os"
)
//var PATHDIR string = "/home/diego/Downloads"
//1234
type login struct {
Status string `json:"status"`
Msg string `json:"msg"`
Token string `json:"token"`
Expires string `json:"expires"`
}
type userLogin struct {
User string `json:"user"`
Password string `json:"password"`
}
func main() {
if len(os.Args) != 4 {
fmt.Println("Entre com os parametros")
fmt.Println(" -path <diretorio onde estara os arquivos>")
fmt.Println(" -user <[email protected]>")
fmt.Println(" -senha <1234>")
os.Exit(0)
}
pathdir := os.Args[1] //Receive path of the files.
user := os.Args[2] //Receive user for login.
pass := os.Args[3] //Receive pass for login.
apiUrl := "https://fileserver.s3apis.com/"
resource := "/v1/user/login"
u, _ := url.ParseRequestURI(apiUrl)
u.Path = resource
urlStr := u.String()
client := &http.Client{}
userjson := &userLogin{User: user, Password: pass}
bjson, err := json.Marshal(userjson)
if err != nil {
log.Fatal("Erro ao fazer Marshal!")
return
}
r, _ := http.NewRequest("POST", urlStr, bytes.NewBuffer(bjson)) // URL-encoded payload
r.Header.Add("X-Key", "ZmlsZXNlcnZlcjIwMThnb2xhbmdiaA==")
r.Header.Add("Content-Type", "application/json")
resp, _ := client.Do(r)
defer resp.Body.Close()
if resp.StatusCode == 200 {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal("Erro na leitura")
return
}
ret := login{}
err = json.Unmarshal(body, &ret)
if err != nil {
log.Println("Erro ao ler json")
}
// pegando o retorno
fmt.Println(string(ret.Msg))
fmt.Println(string(ret.Status))
fmt.Println(string(ret.Expires))
fmt.Println(string(ret.Token))
// pode fazer..
if ret.Status == "ok" && ret.Token != "" {
if !verifyIsDir(pathdir) {
log.Println("Doe's not an directoris valid or not exists.")
return
}
/**
read of the dir
*/
files, err := ioutil.ReadDir(pathdir)
if err != nil {
log.Fatal(err)
}
/**
execute loop in files of the dir's
*/
resource = "/v1/file/upload"
u2, _ := url.ParseRequestURI(apiUrl)
u2.Path = resource
urlStr := u2.String()
for _, file := range files {
if !file.IsDir() {
pathdirNowFile := pathdir + "/" + file.Name()
postFile(ret.Token, pathdirNowFile, urlStr)
}
}
}
} else {
}
/**
curl -X POST https://fileserver.s3apis.com/v1/file/upload --form "file=@seuarquivo" -H "Authorization: Bearer <token>"
verifica if is dir valid
*/
}
func verifyIsDir(pathDir string) bool {
if stat, err := os.Stat(pathDir); err == nil && stat.IsDir() {
return true
}
return false
}
func postFile(Token, filename string, targetUrl string) error {
bodyBuf := &bytes.Buffer{}
bodyWriter := multipart.NewWriter(bodyBuf)
// this step is very important
fileWriter, err := bodyWriter.CreateFormFile("file", filename)
if err != nil {
fmt.Println("error writing to buffer")
return err
}
// open file handle
fh, err := os.Open(filename)
if err != nil {
fmt.Println("error opening file")
return err
}
defer fh.Close()
//iocopy
_, err = io.Copy(fileWriter, fh)
if err != nil {
return err
}
contentType := bodyWriter.FormDataContentType()
bodyWriter.Close()
client := &http.Client{}
//postData := make([]byte, 100)
resp, err := http.NewRequest("POST", targetUrl, bodyBuf)
if err != nil {
return err
}
resp.Header.Add("Content-Type", contentType)
resp.Header.Add("Authorization", "Bearer "+Token)
resp2, err := client.Do(resp)
defer resp2.Body.Close()
fmt.Println(resp2)
return nil
}
// Creates a new file upload http request with optional extra params
func newfileUploadRequest(uri string, params map[string]string, paramName, path string) (*http.Request, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
fileContents, err := ioutil.ReadAll(file)
if err != nil {
return nil, err
}
fi, err := file.Stat()
if err != nil {
return nil, err
}
file.Close()
body := new(bytes.Buffer)
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile(paramName, fi.Name())
if err != nil {
return nil, err
}
// copy...
//io.Copy(part, file)
part.Write(fileContents)
for key, val := range params {
_ = writer.WriteField(key, val)
}
err = writer.Close()
if err != nil {
return nil, err
}
return http.NewRequest("POST", uri, body)
}