forked from taggledevel2/ratchet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ftp_writer.go
75 lines (63 loc) · 1.8 KB
/
ftp_writer.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
package processors
import (
"io"
"github.com/dailyburn/ratchet/data"
"github.com/dailyburn/ratchet/logger"
"github.com/dailyburn/ratchet/util"
"github.com/jlaffaye/ftp"
)
// FtpWriter type represents an ftp writter processor
type FtpWriter struct {
ftpFilepath string
conn *ftp.ServerConn
fileWriter *io.PipeWriter
authenticated bool
host string
username string
password string
path string
}
// NewFtpWriter instantiates new instance of an ftp writer
func NewFtpWriter(host, username, password, path string) *FtpWriter {
return &FtpWriter{authenticated: false, host: host, username: username, password: password, path: path}
}
// connect - opens a connection to the provided ftp host and then authenticates with the host with the username, password attributes
func (f *FtpWriter) connect(killChan chan error) {
conn, err := ftp.Dial(f.host)
if err != nil {
util.KillPipelineIfErr(err, killChan)
}
lerr := conn.Login(f.username, f.password)
if lerr != nil {
util.KillPipelineIfErr(lerr, killChan)
}
r, w := io.Pipe()
f.conn = conn
go f.conn.Stor(f.path, r)
f.fileWriter = w
f.authenticated = true
}
// ProcessData writes data as is directly to the output file
func (f *FtpWriter) ProcessData(d data.JSON, outputChan chan data.JSON, killChan chan error) {
logger.Debug("FTPWriter Process data:", string(d))
if !f.authenticated {
f.connect(killChan)
}
_, e := f.fileWriter.Write([]byte(d))
if e != nil {
util.KillPipelineIfErr(e, killChan)
}
}
// Finish closes open references to the remote file and server
func (f *FtpWriter) Finish(outputChan chan data.JSON, killChan chan error) {
if f.fileWriter != nil {
f.fileWriter.Close()
}
if f.conn != nil {
f.conn.Logout()
f.conn.Quit()
}
}
func (f *FtpWriter) String() string {
return "FtpWriter"
}