ホームページ  >  記事  >  バックエンド開発  >  Golang を使用して Google ドライブから公開ファイルをダウンロードすると、空の「file.zip」が表示されるのはなぜですか?

Golang を使用して Google ドライブから公開ファイルをダウンロードすると、空の「file.zip」が表示されるのはなぜですか?

Barbara Streisand
Barbara Streisandオリジナル
2024-10-28 05:48:30621ブラウズ

Why am I getting a blank

Golang を使用して Google ドライブからパブリック ファイルをダウンロードする

問題

プログラマが Golang を使用して Google ドライブからパブリック ファイルをダウンロードしようとすると、問題が発生します。共有パブリック ファイルがあるにもかかわらず、現在のコードでは空の「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 ドライブから公開ファイルをダウンロードすると、空の「file.zip」が表示されるのはなぜですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。