dsgdhtr_43654 2016-05-31 09:01 采纳率: 100%
浏览 222
已采纳

通过FTP上传golang并同时获得FTP进度

I've used http://github.com/dutchcoders/goftp to send a file via FTP. It works normally but when I want to upload a file and get that file info (at the same time) It doesn't work!

fileName := "sth"
var err error
var ftp *goftp.FTP

if ftp, err = goftp.Connect("serverip:port"); err != nil {
    fmt.Println(err)
}

defer ftp.Close()

config := tls.Config{
    InsecureSkipVerify: true,
    ClientAuth:         tls.RequestClientCert,
}

if err = ftp.AuthTLS(config); err != nil {
    //      log.Println("1", err)
}

if err = ftp.Login("userName", "pass"); err != nil {
    log.Println("2", err)
}
//
if err = ftp.Cwd("/home/myDir/"); err != nil {
    log.Println("3", err)
}

var file *os.File
if file, err = os.Open(fileName); err != nil {
    log.Println("6", err)
}
defer file.Close()

fmt.Println("start")

go func() {
    fmt.Println("first")
    nmp := ftp.Stor(fileName, file)
    if nmp != nil {
        log.Println("7", err)
    } else {
        fmt.Println("first is runung")

    }
}()

go func() {
    fmt.Println("second")
    for {
        files, nms := ftp.List(fileName)
        if nms == nil {
            fmt.Println(files)
        }
        time.Sleep(1 * time.Second)
    }
}()

fmt.Println("end")

var mnmn string
fmt.Scan(&mnmn)

ftp.Stor func won't run and my code returns below outputs:

start
end
first
second
2016/05/31 13:21:38 7 <nil>
[]
[]
  • 写回答

1条回答 默认 最新

  • dreamer1231 2016-05-31 11:42
    关注

    Currently, both the goroutine have same ftp instance (var ftp *goftp.FTP ) which are blocking each other as they have race condition. And your result is unpredictable. Sometime, it gives correct result when first execute properly. Or when it waits for second and then runs completely. Or when first doesn't execute. Otherwise, both the go routine are blocking each other. Solutons:

    • You take two different instances of ftp to give different connections to goroutine

      var ftp,ftp1 *goftp.FTP
      

    Like here Play Golang Or

    • Have *goftp stor first in main go routine. Then start other go routine. But it will defeat the purpose of second go routine.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题