go - 使用 goftp 列出 FTP 文件
问题描述
我正在尝试编写一个简单的 Go 程序,它连接到 FTP 服务器,列出指定目录中的文件并拉取它们。
代码是这样的:
package main
import (
"bytes"
"fmt"
"github.com/secsy/goftp"
"io/ioutil"
"log"
"os"
"path"
"time"
)
func main() {
config := goftp.Config{
User: "anonymous",
Password: "root@local.me",
ConnectionsPerHost: 21,
Timeout: 10 * time.Second,
Logger: os.Stderr,
}
// Connecting to the server
client, dailErr := goftp.DialConfig(config, "ftp.example.com")
if dailErr != nil {
log.Fatal(dailErr)
panic(dailErr)
}
// setting the search directory
dir := "/downloads/"
files, err := client.ReadDir(dir)
if err != nil {
for _, file := range files {
if file.IsDir() {
path.Join(dir, file.Name())
} else {
fmt.Println("the file is %s", file.Name())
}
}
}
// this section works , I am setting a file name and I can pull it
// if I mark the search part
ret_file := "example.PDF"
fmt.Println("Retrieving file: ", ret_file)
buf := new(bytes.Buffer)
fullPathFile := dir + ret_file
rferr := client.Retrieve(fullPathFile, buf)
if rferr != nil {
panic(rferr)
}
fmt.Println("writing data to file", ret_file)
fmt.Println("Opening file", ret_file, "for writing")
w, _ := ioutil.ReadAll(buf)
ferr := ioutil.WriteFile(ret_file, w, 0644)
if ferr != nil {
log.Fatal(ferr)
panic(ferr)
} else {
fmt.Println("Writing", ret_file, " completed")
}
}
出于某种原因,我在ReadDir
功能上遇到错误。我需要获取文件名以便下载它们。
解决方案
files
当ReadDir()
返回错误时,您正在尝试循环。这永远不会奏效,因为任何时候返回错误files
都是nil
.
这是非常标准的行为,可以通过阅读.ReadDir()
我猜您可能已经使用了项目中用于演示的示例ReadDir()
作为起点。在示例中,涉及错误处理,因为它决定是否继续遍历目录树。但是,请注意,当ReadDir()
返回不会导致程序停止的错误时,后续的 for 循环是无操作的,因为files
is nil
。
这是一个小程序,它Readdir()
以简单的方式成功地演示了使用结果:
package main
import (
"fmt"
"github.com/secsy/goftp"
)
const (
ftpServerURL = "ftp.us.debian.org"
ftpServerPath = "/debian/"
)
func main() {
client, err := goftp.Dial(ftpServerURL)
if err != nil {
panic(err)
}
files, err := client.ReadDir(ftpServerPath)
if err != nil {
panic(err)
}
for _, file := range files {
fmt.Println(file.Name())
}
}
它输出(与http://ftp.us.debian.org/debian/上的当前列表相匹配):
$ go run goftp-test.go
README
README.CD-manufacture
README.html
README.mirrors.html
README.mirrors.txt
dists
doc
extrafiles
indices
ls-lR.gz
pool
project
tools
zzz-dists
推荐阅读
- c - 为什么这段代码不能改变(降低)文件的完整性级别?
- c# - 如何创建嵌套属性?C#
- c++ - 如何在 C++11 中将 std::max 与自定义比较器一起使用?
- google-apps-script - Google Apps 脚本 - 2d 变量 - 如何声明?
- c++ - 加权外积的矢量化
- python - 如何根据条件向多个收件人发送个性化电子邮件?
- sql-server - SQL 报表生成器:无法让数据集值出现在报表上
- popover - iOS 13 呈现 iOS 的模态半屏,iPadOS 的弹出框
- linux - 如果第一个字母不是字母,则使用 awk 将一个列值替换为另一个列值
- php - Laravel 从 5.6 升级到 Laravel 6