I've got a program which connects to an SFTP server (hosted in Google Cloud), writes some files and then checks that the file was actually created. Something in the lines of:
outputPath := fmt.Sprintf("%s/%s", "myDir", "myFileName.txt")
// sftpClient is of type *sftp.Client
f, err := sftpClient.OpenFile(outputPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC)
if err != nil {
return nil, fmt.Errorf("failed to create file %s. Error: %s", outputPath, err)
}
defer f.Close()
// write the file
if _, err := f.Write(data); err != nil {
return nil, fmt.Errorf("file %s created by write failed: %s", outputPath, err)
}
// verify if the file exist
_, err := sftpClient.Lstat(outputPath)
if err != nil {
return nil, fmt.Errorf("file %s was written by lstat failed: %s", outputPath, err)
}
...
the file is being written correctly, I can see it in the server in the specified location BUT when it reaches the Lstat command it is throwing an error:
"file /myDir/myFileName.txt was written by Lstat failed: file does not exist"
I'm using the package github.com/pkg/sftp.
Any idea what's going on?
Update
As some of you mentioned I'm closing the file. Yet I'm still seeing the error.
outputPath := fmt.Sprintf("%s/%s", "myDir", "myFileName.txt")
// sftpClient is of type *sftp.Client
f, err := sftpClient.OpenFile(outputPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC)
if err != nil {
return nil, fmt.Errorf("failed to create file %s. Error: %s", outputPath, err)
}
// write the file
if _, err := f.Write(data); err != nil {
return nil, fmt.Errorf("file %s created by write failed: %s", outputPath, err)
}
// closing the file after writing to it
f.Close()
// verify if the file exist
_, err := sftpClient.Lstat(outputPath)
if err != nil {
return nil, fmt.Errorf("file %s was written by lstat failed: %s", outputPath, err)
}
...