Discuss how to transfer files in Golang
With the development of the Internet, file transfer has become an indispensable part of modern society. In programming, file transfer is often necessary, especially in network programming. Golang is a concurrent programming language that is efficient to write and easy to maintain, and it also has many solutions for file transfer. In this article, we will explore how to transfer files in Golang.
1. Use the http package to transfer files
In Golang, you can use the http package to quickly and easily implement file transfer. To do this, we need to create an HTTP server that will respond to client requests and send files to the client.
For example, we can create the following server:
package main import ( "fmt" "net/http" ) func main() { http.HandleFunc("/", func(responseWriter http.ResponseWriter, request *http.Request) { http.ServeFile(responseWriter, request, "example.txt") }) err := http.ListenAndServe(":8080", nil) if err != nil { fmt.Println(err) } }
The above code creates an HTTP server whose main function is to send a file named "example.txt" as a response to the client end. The http.HandleFunc function is used here, which registers "/" as the path and an anonymous function as the handler function. This anonymous function uses the http.ServeFile function to read and send the file. Finally, print error information when err != nil.
It should be noted that before transferring the file, we need to create a text file named "example.txt" and save it in the server directory.
2. Use TCP to transfer files
In Golang, we can also use TCP protocol to transfer files. This method requires creating a client and server to transfer files between them. Here, we need to use the net package, which provides some utility functions and types for socket-based network programming.
The following is an example of using the TCP protocol to transfer files:
- Server:
package main import ( "fmt" "net" "os" ) func main() { // 创建TCP监听器,监听请求 listener, err := net.Listen("tcp", ":8080") if err != nil { fmt.Println("Error listening:", err.Error()) os.Exit(1) } defer listener.Close() fmt.Println("Listening on :8080") // 开始监听 for { // 等待客户端连接 conn, err := listener.Accept() if err != nil { fmt.Println("Error accepting:", err.Error()) continue } // 先读取文件名,再读取文件 fileName := make([]byte, 64) _, err = conn.Read(fileName) if err != nil { fmt.Println("Error reading filename:", err.Error()) continue } file, err := os.Create(string(fileName)) if file != nil { defer file.Close() } if err != nil { fmt.Println("Error create file:", err.Error()) continue } // 开始读取文件内容,并写入本地文件 buf := make([]byte, 1024) for { n, err := conn.Read(buf) if err != nil { fmt.Println("Error reading content:", err.Error()) break } if n == 0 { break } _, err = file.Write(buf[:n]) if err != nil { fmt.Println("Error writing to file:", err.Error()) break } } fmt.Printf("Receive file %s success\n", string(fileName)) } }
The above code creates a TCP server, which will Listen to client requests, read the file content through the file name, and save the file in the current directory. Next, we will send a file to this server through the following client program:
- Client:
package main import ( "fmt" "io/ioutil" "net" "os" ) func main() { // 打开本地文件 file, err := os.Open("example.txt") if err != nil { fmt.Println("Error open file:", err.Error()) os.Exit(1) } defer file.Close() // 连接服务端 conn, err := net.Dial("tcp", "127.0.0.1:8080") if err != nil { fmt.Println("Error connect to server:", err.Error()) os.Exit(1) } defer conn.Close() // 先发送文件名,再发送文件内容 fileName := "example.txt" _, _ = conn.Write([]byte(fileName)) content, err := ioutil.ReadFile(fileName) if err != nil { fmt.Println("Error Read file:", err.Error()) os.Exit(1) } _, err = conn.Write(content) if err != nil { fmt.Println("Error send file:", err.Error()) os.Exit(1) } fmt.Println("Send success") }
The client can send a file named "example. txt" file to the TCP server we created before. The client sends file information to the server by opening a local file and using net.Dial and conn.Write.
Summary:
In Golang, we can use HTTP and TCP protocols to transfer files. The implementation of the HTTP protocol is usually simpler and more convenient, but in some cases it may be more helpful to use the TCP protocol, such as when large files need to be transferred or precise control of file transfers is required. Understanding the pros and cons of both transfer methods and matching them to your needs is crucial to completing a successful file transfer.
The above is the detailed content of Discuss how to transfer files in Golang. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

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

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. �...

Under the BeegoORM framework, how to specify the database associated with the model? Many Beego projects require multiple databases to be operated simultaneously. When using Beego...

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

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

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...
