Go에서 고루틴을 활용하여 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에서 병렬 파일 다운로드

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에서 고루틴을 활용하여 Dropbox에서 여러 파일을 동시에 다운로드하려면 어떻게 해야 하나요?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!