-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathftp.go
89 lines (69 loc) · 1.3 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
package dwnld
import (
"errors"
"io"
"net"
"net/url"
"path"
"time"
"github.com/jlaffaye/ftp"
)
type Ftp struct {
User string
Password string
Host string
Filepath string
}
func (rs *resource) getFtpSrc() (io.ReadCloser, error) {
ft, err := parseFtpUrl(rs.url)
if err != nil {
return nil, err
}
c, err := ftp.Dial(ft.Host, ftp.DialWithTimeout(15*time.Second))
if err != nil {
return nil, err
}
err = c.Login(ft.User, ft.Password)
if err != nil {
return nil, err
}
size, err := c.FileSize(ft.Filepath)
if err != nil {
return nil, err
}
rs.name = path.Base(ft.Filepath)
rs.size = size
return c.Retr(ft.Filepath)
}
func parseFtpUrl(link string) (Ftp, error) {
ftp := Ftp{
User: "anonymous",
Password: "anonymous",
}
u, err := url.Parse(link)
if err != nil {
return ftp, err
}
if name := u.User.Username(); name != "" {
ftp.User = name
}
if pwd, t := u.User.Password(); t && pwd != "" {
ftp.Password = pwd
}
if u.Host == "" {
return ftp, errors.New("parseFtpUrl: invalid host")
}
host, port, _ := net.SplitHostPort(u.Host)
if host == "" {
host = u.Host
}
if port == "" {
port = "21"
}
ftp.Host = host + ":" + port
if u.Path == "" {
return ftp, errors.New("parseFtpUrl: no path found in url")
}
ftp.Filepath = u.Path
return ftp, nil
}