首頁  >  文章  >  後端開發  >  使用 Golang 從 Google Drive 下載公用檔案時,為什麼會出現空白的「file.zip」?

使用 Golang 從 Google Drive 下載公用檔案時,為什麼會出現空白的「file.zip」?

Barbara Streisand
Barbara Streisand原創
2024-10-28 05:48:30621瀏覽

Why am I getting a blank

使用 Golang 從 Google Drive 下載公用檔案

問題

嘗試使用 Golang 從 Google Drive 下載公用檔案的程式設計師遇到了問題。儘管有共享的公共文件,但當前程式碼會建立一個空白的「file.zip」。

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

解決方案

經調查,發現該 URL 重定向到另一個 URL包含特殊字元「*」。 Golang 無法正確處理該字符,將其編碼為“*”而不是“%2A”,從而導致“403 Forbidden”回應。

解決方案是修改程序以處理該特殊字元正確:

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

以上是使用 Golang 從 Google Drive 下載公用檔案時,為什麼會出現空白的「file.zip」?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn