Lv.的博客

go语言实现简易ftp客户端

 
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiangxianghehe/article/details/78310249

Go语言实现的ftp库挺多的,我在这里尝试了一个简单的版本,地址https://github.com/dutchcoders/goftp
先安装依赖:

go get -u -v github.com/dutchcoders/goftp
  • 1

然后配置好ftp服务器,编译执行以下代码,代码包括列出列表和上传功能:

package main

import (
    "github.com/dutchcoders/goftp"
    "fmt"
    "os"
)

func main() {
    var err error
    var ftp *goftp.FTP

    // For debug messages: goftp.ConnectDbg("ftp.server.com:21")
    if ftp, err = goftp.Connect("server_ip:21"); err != nil {
        panic(err)
    }

    defer ftp.Close()
    fmt.Println("Successfully connected !!")


    // Username / password authentication
    if err = ftp.Login("user", "pass"); err != nil {
        panic(err)
    }

    if err = ftp.Cwd("/home/ftp"); err != nil {
        panic(err)
    }

    var curpath string
    if curpath, err = ftp.Pwd(); err != nil {
        panic(err)
    }

    fmt.Printf("Current path: %s", curpath)

    // Get directory listing
    var files []string
    if files, err = ftp.List(""); err != nil {
        panic(err)
    }
    fmt.Println("Directory listing:/n", files)


    // Upload a file
    var file *os.File
    if file, err = os.Open("E://6楼花名册.xlsx"); err != nil {
        panic(err)
    }

    if err := ftp.Stor("/home/ftp/6楼花名册.xlsx", file); err != nil {
        panic(err)
    }

}

 

上传文件代码示例如下:

// Package goftp upload helper
package goftp

import (
    "os"
    "path/filepath"
)

func (ftp *FTP) copyDir(localPath string) error {
    fullPath, err := filepath.Abs(localPath)
    if err != nil {
        return err
    }

    pwd, err := ftp.Pwd()
    if err != nil {
        return err
    }

    walkFunc := func(path string, fi os.FileInfo, err error) error {
        // Stop upon error
        if err != nil {
            return err
        }
        relPath, err := filepath.Rel(fullPath, path)
        if err != nil {
            return err
        }
        switch {
        case fi.IsDir():
            // Walk calls walkFn on root as well
            if path == fullPath {
                return nil
            }
            if err = ftp.Mkd(relPath); err != nil {
                if _, err = ftp.List(relPath + "/"); err != nil {
                    return err
                }
            }
        case fi.Mode()&os.ModeSymlink == os.ModeSymlink:
            fInfo, err := os.Stat(path)
            if err != nil {
                return err
            }
            if fInfo.IsDir() {
                err = ftp.Mkd(relPath)
                return err
            } else if fInfo.Mode()&os.ModeType != 0 {
                // ignore other special files
                return nil
            }
            fallthrough
        case fi.Mode()&os.ModeType == 0:
            if err = ftp.copyFile(path, pwd+"/"+relPath); err != nil {
                return err
            }
        default:
            // Ignore other special files
        }

        return nil
    }

    return filepath.Walk(fullPath, walkFunc)
}

func (ftp *FTP) copyFile(localPath, serverPath string) (err error) {
    var file *os.File
    if file, err = os.Open(localPath); err != nil {
        return err
    }
    defer file.Close()
    if err := ftp.Stor(serverPath, file); err != nil {
        return err
    }

    return nil
}

// Upload a file, or recursively upload a directory.
// Only normal files and directories are uploaded.
// Symlinks are not kept but treated as normal files/directories if targets are so.
func (ftp *FTP) Upload(localPath string) (err error) {
    fInfo, err := os.Stat(localPath)
    if err != nil {
        return err
    }

    switch {
    case fInfo.IsDir():
        return ftp.copyDir(localPath)
    case fInfo.Mode()&os.ModeType == 0:
        return ftp.copyFile(localPath, filepath.Base(localPath))
    default:
        // Ignore other special files
    }

    return nil
}
posted @   Avatarx  阅读(3427)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
历史上的今天:
2014-08-29 QT事件
2014-08-29 自定义QT事件
2014-08-29 qt软键盘输入
2014-08-29 Qt全局热键(windows篇)
2014-08-29 Q_INIT_RESOURCE宏
2014-08-29 QT软键盘
2014-08-29 QtSpeech会让Qt说话
点击右上角即可分享
微信分享提示