ホームページ  >  記事  >  バックエンド開発  >  Go で Goroutines を利用して Dropbox から複数のファイルを同時にダウンロードするにはどうすればよいですか?

Go で Goroutines を利用して Dropbox から複数のファイルを同時にダウンロードするにはどうすればよいですか?

Susan Sarandon
Susan Sarandonオリジナル
2024-10-27 19:46:31637ブラウズ

How can I utilize Goroutines in Go to download multiple files concurrently from Dropbox?

ゴルーチンを使用した Go でのファイルの並列ダウンロード

Go では、ゴルーチンを使用してファイルのダウンロードと保存を同時に行うことができます。ゴルーチンを使用すると、軽量のスレッド実行が可能になり、並列処理が促進され、パフォーマンスが向上します。

ゴルーチンを利用するために変更された、提供されたコードは次のとおりです。

<code class="go">package main

import (
    "encoding/json"
    "fmt"
    "io"
    "io/ioutil"
    "net/http"
    "net/url"
    "os"
    "path/filepath"
    "sync"
)

// Credentials
const app_key string = "<app_key>"
const app_secret string = "<app_secret>"

// Authorization code
var code string

// Token response
type TokenResponse struct {
    AccessToken string `json:"access_token"`
}

// File structure
type File struct {
    Path string
}

// File list response
type FileListResponse struct {
    FileList []File `json:"contents"`
}

// Download a file using goroutines
func download_file(file File, token TokenResponse, wg *sync.WaitGroup) {
    download_file := fmt.Sprintf("https://api-content.dropbox.com/1/files/dropbox/%s?access_token=%s", file.Path, token.AccessToken)

    resp, _ := http.Get(download_file)
    defer resp.Body.Close()

    filename := filepath.Base(file.Path)
    out, err := os.Create(filename)
    if err != nil {
        panic(err)
    }
    defer out.Close()

    io.Copy(out, resp.Body)
    wg.Done()
}

func main() {
    // Authorization and token retrieval
    authorize_url := fmt.Sprintf("https://www.dropbox.com/1/oauth2/authorize?response_type=code&amp;client_id=%s", app_key)
    fmt.Printf("1. Go to: %s\n", authorize_url)
    fmt.Println("2. Click 'Allow' (you might have to log in first)")
    fmt.Println("3. Copy the authorization code.")
    fmt.Printf("Enter the authorization code here: ")
    fmt.Scanf("%s", &amp;code)

    // Get file list
    file_list_url := fmt.Sprintf("https://api.dropbox.com/1/metadata/dropbox/Camera Uploads?access_token=%s", tr.AccessToken)

    resp2, _ := http.Get(file_list_url)
    defer resp2.Body.Close()

    contents2, _ := ioutil.ReadAll(resp2.Body)

    var flr FileListResponse
    json.Unmarshal(contents2, &amp;flr)

    // WaitGroup to wait for all goroutines to finish
    var wg sync.WaitGroup

    // Download files concurrently
    for i, file := range flr.FileList {
        wg.Add(1)

        go download_file(file, tr, &wg)

        if i >= 2 {
            break
        }
    }
    wg.Wait()
}</code>

この変更されたコードでは、同期を追加します。 WaitGroup は wg を呼び出して、実行中のゴルーチンの数を追跡しました。各ゴルーチンを開始する前に wg をインクリメントし、wg.Done() を使用して各ゴルーチンが終了したときにそれをデクリメントします。メインのゴルーチンは、wg.Wait() を呼び出して、すべてのゴルーチンが終了するのを待ちます。これにより、すべてのファイルがダウンロードされる前にプログラムが終了することがなくなります。

以上がGo で Goroutines を利用して Dropbox から複数のファイルを同時にダウンロードするにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

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