I’m trying write a program that will retrieve all files in a directory from a FTP server. The first file is downloaded successfully but on the second file c.Retr(entry)
returns the error:
229 Entering Extended Passive Mode (|||44022|).
I’m obviously lacking some FTP understanding here. I don’t know what to do. I’ve tried providing ftp.DialWithDisabledEPSV(true)
in ftp.Dial(...)
but on the second file c.Retr(entry)
returns the error:
226 Transfer complete
but no file is retrieved.
Below is the code. Please pardon it’s scripty nature. Any assistance greatly appreciated.
package main
import (
"fmt"
"io"
"log"
"os"
"time"
"github.com/jlaffaye/ftp"
)
const (
monthOffset = -1
)
func main() {
c, err := ftp.Dial(
os.Getenv("FTP_HOST"),
ftp.DialWithTimeout(5*time.Second),
)
if err != nil {
log.Fatalln("unable to connect: ", err)
}
err = c.Login(
os.Getenv("ACCOUNT"),
os.Getenv("PASSWORD"),
)
if err != nil {
log.Fatal("login failed: ", err)
}
t := time.Now().AddDate(0, monthOffset, 0)
year, month, _ := t.Date()
path := fmt.Sprintf("%d/%02d/", year, month)
entries, err := c.NameList(path)
if err != nil {
log.Fatalf("unable to NLIST %s: %v\n", path, err)
}
for _, entry := range entries {
fmt.Printf("retrieving %s...\n", entry)
resp, err := c.Retr(entry)
if err != nil {
log.Fatalf("unable to retrieve %s: %v\n", entry, err)
}
defer resp.Close()
if _, err := os.Stat(entry); os.IsNotExist(err) {
os.MkdirAll("data/"+path, 0700)
}
destination, err := os.Create("data/" + entry)
if err != nil {
log.Fatalln("failed to create file:", err)
}
b, err := io.Copy(destination, resp)
if err != nil {
log.Fatalln("unable to copy response to dest file: ", err)
}
fmt.Printf("successfully copied: %s, bytes copied: %d\n", destination.Name(), b)
}
}