Golang Progress Download file

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.
An afternoon that didn't find a job. Code//Very unattractive temporary works package mainimport ("Net/http" "FMT" "OS" "Errors" "IO" "StrConv") func main () { DownloadFile ("Http://localhost:8089/ThunderSpeed1.0.35.366.exe", func (length, Downlen Int64) {FMT. Println (length, Downlen, float32 (downlen)/float32 (length))})}func DownloadFile (URL string, fb func (length, Downlen int   ) Error {var (fsize int64 buf = make ([]byte, 32*1024) written int64)//create an HTTP client Client: = new (http. Client)//get method gets the resource resp, err: = client. Get (URL) if err! = Nil {return ERR}//Read server returns the file size fsize, err = StrConv. parseint (resp. Header.get ("Content-length"), ten, +) if err! = Nil {fmt. PRINTLN (ERR)}//Create file, err: = OS. Create ("Test.exe") if err! = Nil {return err} defer file. Close () If Resp. Body = = Nil {return errors. New ("body is null")} Defer resp. Body.close ()///Below is a simplified version of Io.copybuffer () for {//Read bytes nr, er: = resp. Body.read (bUF) if nr > 0 {//write bytes NW, ew: = file.         Write (BUF[0:NR])//data length greater than 0 if NW > 0 {written + = Int64 (NW)}//write error            If ew! = Nil {err = ew break}//Read is data length not equal to write data length if nr! = NW { Err = io. Errshortwrite break}} if er! = nil {if er! = io. EOF {err = er} break}//No errors soon use callback fb (Fsize, written)} return err }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.