-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.go
100 lines (84 loc) · 2.21 KB
/
client.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
package main
import (
"bytes"
"io"
"mime/multipart"
"net/http"
"os"
"path/filepath"
)
// Interface is FTP client interfaces
type Interface interface {
ReaddirSourceFolder(crontdata Cron) error
SetFilenameToDownload(filename []string)
GetFilenameToDownload() []string
DownloadTempFile(filepath string) error
Close()
}
// InitiateFTPClient will initiates ftp client based on client type, whether it is a FTP/s or SFTP
// By default it will use SFTP
func InitiateFTPClient(clientType string, config *Config) Interface {
host := config.Source.Host
port := config.Source.Port
username := config.Source.Username
password := config.Source.Password
dirpath := config.Source.Folder
var clientSession Interface
switch clientType {
case `sftp`:
clientSession = NewSFTP(host, port, username, password)
break
case `ftps`:
clientSession = NewFTPS(host, port, username, password)
break
case `local`:
clientSession = NewLocalFolder(dirpath)
break
default:
clientSession = NewSFTP(host, port, username, password)
}
return clientSession
}
// Upload is used to uplad download temp file to destination
func Upload(config *Config, tempfilepath string) error {
Logf("Uploading file=%s ...\n", tempfilepath)
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
for _, uploadItem := range config.Target.Upload {
if uploadItem["key"] == uploadItem["value"] {
file, err := os.Open(tempfilepath)
if err != nil {
return err
}
defer file.Close()
part, err := writer.CreateFormFile(uploadItem["key"], filepath.Base(tempfilepath))
if err != nil {
return err
}
_, _ = io.Copy(part, file)
} else {
writer.WriteField(uploadItem["key"], uploadItem["value"])
}
}
errWriterClose := writer.Close()
if errWriterClose != nil {
return errWriterClose
}
req, err := http.NewRequest("POST", config.Target.Host, body)
if err != nil {
return err
}
for _, header := range config.Target.Header {
req.Header.Set(header["key"], header["value"])
}
req.Header.Set("Content-Type", writer.FormDataContentType())
httpclient := &http.Client{}
resp, err := httpclient.Do(req)
if err != nil {
return err
}
if resp.StatusCode != 200 {
return Upload(config, tempfilepath)
}
return nil
}