首頁 > 後端開發 > Golang > 主體

如何利用 Go 中的 Goroutines 從 Dropbox 同時下載多個檔案?

Susan Sarandon
發布: 2024-10-27 19:46:31
原創
636 人瀏覽過

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

Go 中使用 Goroutines 並行檔案下載

在 Go 中,可以使用 Goroutines 並行下載和儲存檔案。 Goroutines 允許輕量級執行緒執行,促進並行處理並提高效能。

這是您提供的程式碼,經過修改以利用 Goroutines:

<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>
登入後複製

在此修改後的程式碼中,我們新增了一個sync.sync。 WaitGroup 呼叫 wg 來追蹤正在執行的 goroutine 數量。我們在啟動每個 goroutine 之前遞增 wg,並在每個 goroutine 使用 wg.Done() 完成時遞減 wg。主協程透過呼叫 wg.Wait() 等待所有協程完成。這可以確保在下載所有文件之前程式不會退出。

以上是如何利用 Go 中的 Goroutines 從 Dropbox 同時下載多個檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!