Home Backend Development Golang Using FTP in Go: A Complete Guide

Using FTP in Go: A Complete Guide

Jun 17, 2023 pm 06:31 PM
go language ftp guide

With the rapid development of the Internet, File Transfer Protocol (FTP) has always been an important file transfer method. In Go language, using FTP to transfer files may be a need of many developers. However, maybe many people don't know how to use FTP in Go language. In this article, we will explore how to use FTP in Go language, from connecting to FTP server to file transfer, and how to handle errors and exceptions.

Create FTP connection

In the Go language, we can use the standard "net" package to connect to the FTP server and perform file transfer operations. First, we need to establish an FTP connection. Using the "net.Dial" function we can create a network connection to communicate with the FTP server. In this example we will use an FTP server.

package main

import (
    "fmt"
    "net"
)

func main() {
    conn, err := net.Dial("tcp", "ftp.mozilla.org:21")
    if err != nil {
        fmt.Println("Error connecting to server:", err)
        return
    }
    fmt.Println("Connected to server")
    conn.Close()
}
Copy after login

Use FTP client to log in to the server

Once the connection is established, we need to use FTP client to log in. Using the "NewConn" function from the "net/textproto" package, we can create a read-write connection to communicate with the FTP server. Next, we need to authenticate using the "Login" function.

package main

import (
    "fmt"
    "net"
    "net/textproto"
)

func main() {
    conn, err := net.Dial("tcp", "ftp.mozilla.org:21")
    if err != nil {
        fmt.Println("Error connecting to server:", err)
        return
    }
    defer conn.Close()
    fmt.Println("Connected to server")

    client := textproto.NewConn(conn)
    _, err = client.Cmd("USER anonymous")
    if err != nil {
        fmt.Println("Error sending user command:", err)
        return
    }
    _, err = client.Cmd("PASS password")
    if err != nil {
        fmt.Println("Error sending password command:", err)
        return
    }
    fmt.Println("Logged in as anonymous")
}
Copy after login

FTP client command

FTP client command sends a command to the FTP server in the form of a string. The following are common FTP client commands:

  • USER - the username to log in to the FTP server.
  • PASS - Password to log in to the FTP server.
  • PWD - Displays the current server directory.
  • CWD - Change the current server directory.
  • LIST - List the files and subdirectories of the current directory.
  • RETR - Download file from server.
  • STOR - Upload files to the server.
  • DELE - Delete a file on the server.
  • RNFR - Rename file source.
  • RNTO - Rename file target.

FTP Client File Upload and Download

Once the connection is established and logged in through the FTP client, we can transfer files. In Go language, transferring files using FTP client is very simple. We just need to use "RETR" command to download files or "STOR" command to upload files. We can use the "Copy" function in the "io" package to copy the file contents from the FTP server to a local file, or to copy the local file contents to the FTP server.

Let’s take a look at how to download files using an FTP client.

package main

import (
    "fmt"
    "io"
    "net"
    "net/textproto"
    "os"
)

func main() {
    conn, err := net.Dial("tcp", "ftp.mozilla.org:21")
    if err != nil {
        fmt.Println("Error connecting to server:", err)
        return
    }
    defer conn.Close()
    fmt.Println("Connected to server")

    client := textproto.NewConn(conn)
    _, err = client.Cmd("USER anonymous")
    if err != nil {
        fmt.Println("Error sending user command:", err)
        return
    }
    _, err = client.Cmd("PASS password")
    if err != nil {
        fmt.Println("Error sending password command:", err)
        return
    }
    fmt.Println("Logged in as anonymous")

    _, err = client.Cmd("TYPE I")
    if err != nil {
        fmt.Println("Error sending type command:", err)
        return
    }

    _, err = client.Cmd("PASV")
    if err != nil {
        fmt.Println("Error sending pasv command:", err)
        return
    }
    response, err := client.ReadLine()
    if err != nil {
        fmt.Println("Error reading pasv response:", err)
        return
    }
    fmt.Println(response)

    _, err = client.Cmd("RETR /pub/README.txt")
    if err != nil {
        fmt.Println("Error sending retr command:", err)
        return
    }

    response, err = client.ReadLine()
    if err != nil {
        fmt.Println("Error reading retr response:", err)
        return
    }
    fmt.Println(response)

    file, err := os.Create("README.txt")
    if err != nil {
        fmt.Println("Error creating file:", err)
        return
    }
    defer file.Close()

    _, err = io.Copy(file, conn)
    if err != nil {
        fmt.Println("Error copying file:", err)
        return
    }

    fmt.Println("Downloaded README.txt")
}
Copy after login

Let’s take a look at how to upload files using an FTP client.

package main

import (
    "fmt"
    "io"
    "net"
    "net/textproto"
    "os"
)

func main() {
    conn, err := net.Dial("tcp", "ftp.mozilla.org:21")
    if err != nil {
        fmt.Println("Error connecting to server:", err)
        return
    }
    defer conn.Close()
    fmt.Println("Connected to server")

    client := textproto.NewConn(conn)
    _, err = client.Cmd("USER anonymous")
    if err != nil {
        fmt.Println("Error sending user command:", err)
        return
    }
    _, err = client.Cmd("PASS password")
    if err != nil {
        fmt.Println("Error sending password command:", err)
        return
    }
    fmt.Println("Logged in as anonymous")

    _, err = client.Cmd("TYPE I")
    if err != nil {
        fmt.Println("Error sending type command:", err)
        return
    }

    _, err = client.Cmd("PASV")
    if err != nil {
        fmt.Println("Error sending pasv command:", err)
        return
    }
    response, err := client.ReadLine()
    if err != nil {
        fmt.Println("Error reading pasv response:", err)
        return
    }
    fmt.Println(response)

    _, err = client.Cmd("STOR /public_html/test.txt")
    if err != nil {
        fmt.Println("Error sending stor command:", err)
        return
    }

    file, err := os.Open("test.txt")
    if err != nil {
        fmt.Println("Error opening file:", err)
        return
    }
    defer file.Close()

    _, err = io.Copy(conn, file)
    if err != nil {
        fmt.Println("Error copying file:", err)
        return
    }

    response, err = client.ReadLine()
    if err != nil {
        fmt.Println("Error reading store response:", err)
        return
    }
    fmt.Println(response)

    fmt.Println("Uploaded test.txt")
}
Copy after login

Handling Errors and Exceptions

When using an FTP client for file transfer, it is very important to handle exceptions and errors. When errors occur, the client needs to be able to return error information to the user so they can identify the problems and resolve them. Below is an example using an FTP client that demonstrates how to handle errors and exceptions.

package main

import (
    "fmt"
    "io"
    "net"
    "net/textproto"
    "os"
)

func main() {
    conn, err := net.Dial("tcp", "ftp.mozilla.org:21")
    if err != nil {
        fmt.Println("Error connecting to server:", err)
        return
    }
    defer conn.Close()
    fmt.Println("Connected to server")

    client := textproto.NewConn(conn)
    _, err = client.Cmd("USER anonymous")
    if err != nil {
        fmt.Println("Error sending user command:", err)
        return
    }
    _, err = client.Cmd("PASS password")
    if err != nil {
        fmt.Println("Error sending password command:", err)
        return
    }
    fmt.Println("Logged in as anonymous")

    _, err = client.Cmd("TYPE I")
    if err != nil {
        fmt.Println("Error sending type command:", err)
        return
    }

    _, err = client.Cmd("PASV")
    if err != nil {
        fmt.Println("Error sending pasv command:", err)
        return
    }
    response, err := client.ReadLine()
    if err != nil {
        fmt.Println("Error reading pasv response:", err)
        return
    }
    fmt.Println(response)

    _, err = client.Cmd("RETR /pub/README.txt")
    if err != nil {
        fmt.Println("Error sending retr command:", err)
        return
    }

    response, err = client.ReadLine()
    if err != nil {
        fmt.Println("Error reading retr response:", err)
        return
    }
    fmt.Println(response)

    file, err := os.Create("README.txt")
    if err != nil {
        fmt.Println("Error creating file:", err)
        return
    }
    defer file.Close()

    _, err = io.Copy(file, conn)
    if err != nil {
        fmt.Println("Error copying file:", err)
        return
    }

    fmt.Println("Downloaded README.txt")

    _, err = client.Cmd("QUIT")
    if err != nil {
        fmt.Println("Error sending quit command:", err)
        return
    }
}
Copy after login

Conclusion

In this article, we have learned how to use FTP in Go language, including establishing FTP connection, using FTP client to log in to FTP server, FTP client commands, file upload and downloads, and how to handle errors and exceptions. Using FTP to transfer files may be a need of many developers. It is not difficult to use FTP client in Go language because we can use the "net" and "io" packages in the standard library to create FTP connections and perform file transfers. Next, you can use this knowledge to develop your own FTP client, or handle your own file transfer needs.

The above is the detailed content of Using FTP in Go: A Complete Guide. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

What is the difference between `var` and `type` keyword definition structure in Go language? What is the difference between `var` and `type` keyword definition structure in Go language? Apr 02, 2025 pm 12:57 PM

Two ways to define structures in Go language: the difference between var and type keywords. When defining structures, Go language often sees two different ways of writing: First...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

Why is it necessary to pass pointers when using Go and viper libraries? Why is it necessary to pass pointers when using Go and viper libraries? Apr 02, 2025 pm 04:00 PM

Go pointer syntax and addressing problems in the use of viper library When programming in Go language, it is crucial to understand the syntax and usage of pointers, especially in...

Why do all values ​​become the last element when using for range in Go language to traverse slices and store maps? Why do all values ​​become the last element when using for range in Go language to traverse slices and store maps? Apr 02, 2025 pm 04:09 PM

Why does map iteration in Go cause all values ​​to become the last element? In Go language, when faced with some interview questions, you often encounter maps...

See all articles