首页  >  文章  >  后端开发  >  如何利用 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 中使用 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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn