私はGo
に新しく、複数のURLをプログレスバーとともにダウンロードできるクロスブラウザアプリケーションを作成しようとしています。 Grab
パッケージは下の例のようにうまく機能します。今、私は自己完結型/ポータブル/単一実行可能なウェブUIを持っていて、下のコードからのダウンロードの進捗状況をWebブラウザで表示できますか?溶液のGolangとローカルWebインターフェイスのダウンロードが進んでいますか?
package main
import (
"fmt"
"github.com/cavaliercoder/grab"
"os"
"time"
)
func main() {
// get URL to download from command args
if len(os.Args) < 2 {
fmt.Fprintf(os.Stderr, "usage: %s url [url]...\n", os.Args[0])
os.Exit(1)
}
urls := os.Args[1:]
// start file downloads, 3 at a time
fmt.Printf("Downloading %d files...\n", len(urls))
respch, err := grab.GetBatch(3, ".", urls...)
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
// start a ticker to update progress every 200ms
t := time.NewTicker(200 * time.Millisecond)
// monitor downloads
completed := 0
inProgress := 0
responses := make([]*grab.Response, 0)
for completed < len(urls) {
select {
case resp := <-respch:
// a new response has been received and has started downloading
// (nil is received once, when the channel is closed by grab)
if resp != nil {
responses = append(responses, resp)
}
case <-t.C:
// clear lines
if inProgress > 0 {
fmt.Printf("\033[%dA\033[K", inProgress)
}
// update completed downloads
for i, resp := range responses {
if resp != nil && resp.IsComplete() {
// print final result
if resp.Error != nil {
fmt.Fprintf(os.Stderr, "Error downloading %s: %v\n", resp.Request.URL(), resp.Error)
} else {
fmt.Printf("Finished %s %d/%d bytes (%d%%)\n", resp.Filename, resp.BytesTransferred(), resp.Size, int(100*resp.Progress()))
}
// mark completed
responses[i] = nil
completed++
}
}
// update downloads in progress
inProgress = 0
for _, resp := range responses {
if resp != nil {
inProgress++
fmt.Printf("Downloading %s %d/%d bytes (%d%%)\033[K\n", resp.Filename, resp.BytesTransferred(), resp.Size, int(100*resp.Progress()))
}
}
}
}
t.Stop()
fmt.Printf("%d files successfully downloaded.\n", len(urls))
}
あなたはUIのプログレスバーが必要です、またはあなたが望むにダウンロードの進行状況を表示しますか? –
このコードからダウンロード進行状況を表示する必要があります。fmt.Printf( "%s%d /%dバイト(%d %%)をダウンロード中です。\ 033 [K \ n "、resp.Filename、resp.BytesTransferred()、resp.Size、int(100 * resp.Progress()))'を実行します。 – iLearn2016
次に、この場合にはwebsocketを使用する必要があると思います。 –