Golang Go語言斷點續傳

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
package mainimport (    "http"    "os"    "io"    "strconv")const (    UA = "Golang Downloader from Kejibo.com")func main() {    f, err := os.OpenFile("./file.exe", os.O_RDWR, 0666)  //其實這裡的 O_RDWR應該是 O_RDWR|O_CREATE,也就是檔案不存在的情況下就建一個空檔案,但是因為windows下還有BUG,如果使用這個O_CREATE,就會直接清空檔案,所以這裡就不用了這個標誌,你自己事先建立好檔案。    if err != nil { panic(err) }    stat, err := f.Stat()   //擷取檔案狀態    if err != nil { panic(err) }    f.Seek(stat.Size, 0)    //把檔案指標指到檔案末,當然你說為何不直接用 O_APPEND 模式開啟,沒錯是可以。我這裡只是實驗。    url := "http://dl.google.com/chrome/install/696.57/chrome_installer.exe"    var req http.Request    req.Method = "GET"    req.UserAgent = UA    req.Close = true    req.URL, err = http.ParseURL(url)    if err != nil { panic(err) }    header := http.Header{}    header.Set("Range", "bytes=" + strconv.Itoa64(stat.Size) + "-")    req.Header = header    resp, err := http.DefaultClient.Do(&req)    if err != nil { panic(err) }    written, err := io.Copy(f, resp.Body)    if err != nil { panic(err) }    println("written: ", written)}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.