golang实现一个简单的FTP服务器

分类:技术文档 - Golang | 阅读(6964) | 发布于:2019-04-02 14:53

使用golang实现一个简单的ftp服务器,方便传文件

使用:
ftpd.exe [-user=admin] [-pass=123456] [-root=C:\www] [-host=0.0.0.0] [-post=21]
可双击打开直接运行,即使用默认配置.
默认 用户名:admin (-user=admin)
密码:123456 (-pass=123456)
根目录:(-root=当前执行文件所在目录)

下载Windows版本:ftpd.exe

源码:(运行后程序会自动生成 code/main.go 的源文件)

package main

import (
	"flag"
	"log"

	"github.com/goftp/file-driver"
	"github.com/goftp/server"
	"path/filepath"
	"os"
	"strings"
	"fmt"
)

func init() {

	/*
	err := asset.RestoreAssets("./", "code")
	if err != nil {
		fmt.Println("RestoreAssets code error", "\n", err, "\n")
	}
	*/

	fmt.Println("to build exe file usage:")
	fmt.Println("go-bindata -o asset/bindata.go -pkg asset code")
	fmt.Println(`go build -o ftpd.exe code\main.go`)
	fmt.Println()
}

func main() {
	var (
		root = flag.String("root", getCurrentDirectory(), "Root directory to serve")
		user = flag.String("user", "admin", "Username for login")
		pass = flag.String("pass", "123456", "Password for login")
		port = flag.Int("port", 21, "Port")
		host = flag.String("host", "0.0.0.0", "Port")
	)
	flag.Parse()

	if *root == "" {
		*root = getCurrentDirectory()
	}

	factory := &filedriver.FileDriverFactory{
		RootPath: *root,
		Perm:     server.NewSimplePerm("user", "group"),
	}

	opts := &server.ServerOpts{
		Factory:  factory,
		Port:     *port,
		Hostname: *host,
		Auth:     &server.SimpleAuth{Name: *user, Password: *pass},
	}

	log.Printf("Starting ftp server on \n"+
		"Host      %v \n"+
		"Port      %v \n"+
		"Username  %v \n"+
		"Password  %v \n"+
		"RootDir   %s \n\n",
		opts.Hostname, opts.Port, *user, *pass, factory.RootPath)

	ftpServer := server.NewServer(opts)
	err := ftpServer.ListenAndServe()
	if err != nil {
		log.Fatal("Error starting server:", err)
	}
}

func getCurrentDirectory() string {
	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		log.Fatal(err)
	}
	return strings.Replace(dir, "\\", "/", -1)
}

标签: