Home  >  Article  >  Backend Development  >  Golang implements file download

Golang implements file download

王林
王林Original
2023-05-14 20:08:382760browse

golang implements file download

In the Internet era, we cannot do without file download, but few people care about the specific implementation process of file download. Today we will introduce how to implement file downloading in golang.

For the convenience of display, we select a file available on the network. Assume that the address of the file we need to download is: http://files.saas.hand-china.com/java/sales-hardware-management .pdf

First, we need to introduce golang’s built-in http package and os package:

import (
    "fmt"
    "net/http"
    "os"
)

Then, we can get the response result of the file that needs to be downloaded through http.Get:

response, err := http.Get(url)
if err != nil {
    fmt.Println("Error fetching response. ", err)
    return
}
defer response.Body.Close()

It should be noted that after obtaining the response result, we need to close response.Body at the appropriate time.

Next, we can create the file that needs to be saved through os.Create:

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

where filepath is the path of the file we need to save.

Finally, we can write the response result to the file just created through io.Copy:

_, err = io.Copy(out, response.Body)
if err != nil {
    fmt.Println("Error saving file. ", err)
    return
}

fmt.Println("File saved successfully.")

The complete golang code is as follows:

package main

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

func main() {
    url := "http://files.saas.hand-china.com/java/sales-hardware-management.pdf"
    filepath := "sales-hardware-management.pdf"

    response, err := http.Get(url)
    if err != nil {
        fmt.Println("Error fetching response. ", err)
        return
    }
    defer response.Body.Close()

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

    _, err = io.Copy(out, response.Body)
    if err != nil {
        fmt.Println("Error saving file. ", err)
        return
    }

    fmt.Println("File saved successfully.")
}

The above is the golang implementation A brief introduction and demonstration of file downloading. I believe that with this example, everyone will have a deeper understanding of the implementation process of file downloading.

The above is the detailed content of Golang implements file download. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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