forked from gobackup/gobackup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ftp.go
91 lines (76 loc) 路 1.71 KB
/
ftp.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
package storage
import (
"os"
"path"
"github.com/auzty/gobackup/helper"
// "crypto/tls"
"time"
"github.com/auzty/gobackup/logger"
"github.com/secsy/goftp"
)
// FTP storage
//
// type: ftp
// path: /backups
// host: ftp.your-host.com
// port: 21
// timeout: 30
// username:
// password:
type FTP struct {
Base
path string
host string
port string
username string
password string
client *goftp.Client
}
func (ctx *FTP) open() (err error) {
ctx.viper.SetDefault("port", "21")
ctx.viper.SetDefault("timeout", 300)
ctx.host = helper.CleanHost(ctx.viper.GetString("host"))
ctx.port = ctx.viper.GetString("port")
ctx.path = ctx.viper.GetString("path")
ctx.username = ctx.viper.GetString("username")
ctx.password = ctx.viper.GetString("password")
ftpConfig := goftp.Config{
User: ctx.viper.GetString("username"),
Password: ctx.viper.GetString("password"),
Timeout: ctx.viper.GetDuration("timeout") * time.Second,
}
ctx.client, err = goftp.DialConfig(ftpConfig, ctx.host+":"+ctx.port)
if err != nil {
return err
}
return
}
func (ctx *FTP) close() {
ctx.client.Close()
}
func (ctx *FTP) upload(fileKey string) (err error) {
logger.Info("-> Uploading...")
_, err = ctx.client.Stat(ctx.path)
if os.IsNotExist(err) {
if _, err := ctx.client.Mkdir(ctx.path); err != nil {
return err
}
}
file, err := os.Open(ctx.archivePath)
if err != nil {
return err
}
defer file.Close()
remotePath := path.Join(ctx.path, fileKey)
err = ctx.client.Store(remotePath, file)
if err != nil {
return err
}
logger.Info("Store successed")
return nil
}
func (ctx *FTP) delete(fileKey string) (err error) {
remotePath := path.Join(ctx.path, fileKey)
err = ctx.client.Delete(remotePath)
return
}