Home > Article > Backend Development > How to Download Public Files from Google Drive in Golang: Why Is My Zip File Empty?
Downloading Public Files from Google Drive in Golang
In this article, we'll explore how to download a publicly shared zip file from Google Drive using Golang.
Problem Statement
Consider the following code snippet that attempts to download a zip file from Google Drive:
<code class="go">package main import ( "fmt" "io" "net/http" "os" ) func main() { 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() response, err := http.Get(url) if err != nil { fmt.Println("Error while downloading", url, "-", eerrror) return } defer response.Body.Close() n, err := io.Copy(output, response.Body) fmt.Println(n, "bytes downloaded") }</code>
However, this code only creates an empty file named "file.zip" instead of downloading the zip file from Google Drive.
Troubleshooting the Problem
Upon further investigation, it was discovered that Google Drive redirects the initial download URL to a second URL with an asterisk character () in its path. Unfortunately, the Go HTTP client encodes the asterisk as "*" instead of resolving it to a , resulting in a "403 Forbidden" response from Google Drive.
Solution
To resolve this issue, you can manually manipulate the URL to remove the asterisk character and encode it correctly as per RFC 3986. The modified code snippet would look like this:
<code class="go">package main import ( "fmt" "io" "net/http" "os" "strings" ) func main() { url := "https://docs.google.com/uc?export=download&id=0B2Q7X-dUtUBebElySVh1ZS1iaTQ" fileName := "file.zip" fmt.Println("Downloading file...") // Replace the %2A with the asterisk character url = strings.Replace(url, "%2A", "*", -1) output, err := os.Create(fileName) defer output.Close() response, err := http.Get(url) if err != nil { fmt.Println("Error while downloading", url, "-", err) return } defer response.Body.Close() n, err := io.Copy(output, response.Body) fmt.Println(n, "bytes downloaded") }</code>
By manually replacing the "*" with the asterisk character, the code successfully downloads the zip file from Google Drive.
The above is the detailed content of How to Download Public Files from Google Drive in Golang: Why Is My Zip File Empty?. For more information, please follow other related articles on the PHP Chinese website!