Introduction
Creating an FTP (File Transfer Protocol) server can be a straightforward process, especially if you're wanting to handle simple file uploads and downloads for personal or lightweight applications. This article will guide you through building a minimal FTP server in the Go programming language.
Prerequisites
- Basic understanding of Go programming language.
- Go should be installed on your system (installation guide).
Step 1: Setting Up a Go Module
Firstly, create a new directory for your project and initialize a new Go module.
mkdir go-ftp-server
cd go-ftp-server
go mod init go-ftp-serverStep 2: Installing Dependencies
We're going to use a library called "goftp" to handle FTP functionalities. Run the following command to install:
go get github.com/goftp/serverStep 3: Writing the FTP Server Code
Create a new Go file named main.go and add the following content:
package main
import (
"flag"
"log"
"github.com/goftp/server"
)
func main() {
user := flag.String("user", "admin", "Username for the FTP server.")
pass := flag.String("pass", "123456", "Password for the FTP server.")
root := flag.String("root", "/tmp", "Root directory for the FTP server.")
address := flag.String("address", ":2121", "Port and address to run the FTP server on.")
flag.Parse()
opts := &server.ServerOpts{
Factory: &server.SimplePerm{RootPath: *root},
Port: ":2121",
Auth: &server.SimpleAuth{
Name: *user,
Pass: *pass,
},
}
ftpServer := server.NewServer(opts)
log.Printf("Starting FTP server on %s", *address)
err := ftpServer.ListenAndServe()
if err != nil {
log.Fatal("Error starting server: ", err)
}
}This simple server listens on port 2121, with a default username "admin" and password "123456", serving files from the /tmp directory. You can easily change these defaults with command-line flags.
Step 4: Running the FTP Server
Compile and run your FTP server with:
go run main.goNow you can connect to your server using an FTP client with the credentials specified in the flags.
Conclusion
You've just seen a simple way to set up an FTP server using the Go programming language. This server is basic and used primarily for learning purposes. Writing an actual production-ready FTP server would require more attention to security, efficient file handling, and other robust features. For those interested in further enhancing this server, consider digging deeper into the Go standard library or relying on third-party packages for more advanced functionalities.