Home Backend Development Golang How to use network programming functions in Go language to implement HTTP server downloading files?

How to use network programming functions in Go language to implement HTTP server downloading files?

Jul 29, 2023 am 11:57 AM
go language network programming http server download file

How to use network programming functions in Go language to implement HTTP server download files?

Network programming plays an important role in modern software development. Using the Go language, we can easily implement an HTTP server so that it can provide file download functions. This article will introduce how to use the network programming functions in the Go language to implement a simple HTTP server to realize the file download function.

  1. Import required packages

First, we need to import some required packages. In Go language, we can use "net/http" and "os" packages to implement HTTP server and file operations.

1

2

3

4

5

6

7

package main

 

import (

    "fmt"

    "net/http"

    "os"

)

Copy after login
  1. Implementing the HTTP server

Next, we will create a processor function to handle HTTP requests from the client. In this example, we will implement a simple download function. The client passes the file name through a GET request, and the server will return the file to the client.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

func fileHandler(w http.ResponseWriter, r *http.Request) {

    // 获取文件名

    filename := r.URL.Query().Get("filename")

   

    // 打开文件

    file, err := os.Open(filename)

    if err != nil {

        // 文件不存在或无法打开,返回404

        http.NotFound(w, r)

        return

    }

    defer file.Close()

   

    // 设置响应头

    fileInfo, _ := file.Stat()

    w.Header().Set("Content-Disposition", "attachment; filename="+filename)

    w.Header().Set("Content-Type", "application/octet-stream")

    w.Header().Set("Content-Length", fmt.Sprintf("%d", fileInfo.Size()))

   

    // 发送文件给客户端

    http.ServeContent(w, r, filename, fileInfo.ModTime(), file)

}

Copy after login

In this processor function, we first get the file name passed by the client. Then we open the file and do error checking. If the file does not exist or cannot be opened, we will return a 404 error to the client. If the file opens successfully, we set response headers including the downloaded file name, type, and length. Finally, we use the http.ServeContent function to send the file content to the client.

  1. Register processor function

In the main function, we need to register the processor function and bind it to a path, So that clients can access the service through this path. In this example, we register the handler function on the "/download" path.

1

2

3

4

func main() {

    http.HandleFunc("/download", fileHandler)

    http.ListenAndServe(":8000", nil)

}

Copy after login

We use the http.HandleFunc function to register the processor function on the specified path. Then, we call the http.ListenAndServe function to listen to the specified port in order to receive requests from the client.

  1. Run the server

Now that we have completed the implementation of the HTTP server, we can run the server and test the download functionality. Run go run main.go on the command line to start the server. The server will listen on port 8000 and wait for client requests.

When the client accesses http://localhost:8000/download?filename=test.txt, the server will try to open the file named test.txt file and send it to the client. If the file does not exist, the server will return a 404 error.

Through the above code example, we can see that it is very simple to implement an HTTP server to download files using the network programming functions provided by the Go language. Through this example, we can understand the powerful functions of Go language in network programming and how to use these functions to achieve actual application requirements.

The above is the detailed content of How to use network programming functions in Go language to implement HTTP server downloading files?. 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

Video Face Swap

Video Face Swap

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

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)

How to convert XML to PDF on your phone? How to convert XML to PDF on your phone? Apr 02, 2025 pm 10:18 PM

It is not easy to convert XML to PDF directly on your phone, but it can be achieved with the help of cloud services. It is recommended to use a lightweight mobile app to upload XML files and receive generated PDFs, and convert them with cloud APIs. Cloud APIs use serverless computing services, and choosing the right platform is crucial. Complexity, error handling, security, and optimization strategies need to be considered when handling XML parsing and PDF generation. The entire process requires the front-end app and the back-end API to work together, and it requires some understanding of a variety of technologies.

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

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

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

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

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

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

See all articles