Home  >  Article  >  Backend Development  >  Why am I getting a blank \"file.zip\" when downloading public files from Google Drive using Golang?

Why am I getting a blank \"file.zip\" when downloading public files from Google Drive using Golang?

Barbara Streisand
Barbara StreisandOriginal
2024-10-28 05:48:30621browse

Why am I getting a blank

Download Public Files from Google Drive Using Golang

Problem

Programmers attempting to download public files from Google Drive using Golang are encountering issues. Despite having a shared public file, current code results in a blank "file.zip" being created.

<code class="go">import (
    "fmt"
    "io"
    "net/http"
    "os"
)

// Main function
func main() {
    url := "https://docs.google.com/uc?export=download&amp;id=0B2Q7X-dUtUBebElySVh1ZS1iaTQ"
    fileName := "file.zip"
    fmt.Println("Downloading file...")
    output, err := os.Create(fileName)
    defer output.Close()
    response, err := http.Get(url)
    if err != nil {
        fmt.Println("Error while downloading", url, "-", error)
        return
    }
    defer response.Body.Close()
    n, err := io.Copy(output, response.Body)
    fmt.Println(n, "bytes downloaded")
}</code>

Solution

Upon investigation, it was discovered that the URL redirects to another URL containing a special character "*". This character is not handled correctly by Golang, which encoded it as "*" instead of "%2A", resulting in a "403 Forbidden" response.

The solution is to modify the program to handle the special character correctly:

<code class="go">url := "https://docs.google.com/uc?export=download&id=0B2Q7X-dUtUBebElySVh1ZS1iaTQ"
fileName := "file.zip"
fmt.Println("Downloading file...")
output, err := os.Create(fileName)
defer output.Close()

url = strings.Replace(url, "%2A", "%252A", -1) // Replace * with its percent-encoded form

response, err := http.Get(url)</code>

The above is the detailed content of Why am I getting a blank \"file.zip\" when downloading public files from Google Drive using Golang?. 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