Skip to content

Commit

Permalink
add: sync pool && Download method moved to Download
Browse files Browse the repository at this point in the history
  • Loading branch information
melbahja committed Aug 15, 2020
1 parent 913a3d0 commit 7866184
Showing 1 changed file with 16 additions and 36 deletions.
52 changes: 16 additions & 36 deletions chunk.go
Original file line number Diff line number Diff line change
@@ -1,56 +1,36 @@
package got

import (
"fmt"
"io"
"net/http"
"os"
"sync"
)

// Chunk is a part of file.
// Chunk is a partial content range.
type Chunk struct {

// Progress to report written bytes.
*Progress

// Chunk start pos.
Start uint64

// Chunk end.
// Chunk end pos.
End uint64

// Path name where this chunk downloaded.
Path string

// Done to check is this chunk downloaded.
Done chan struct{}
}

// Download a chunk, and report to Progress, it returns error if any!
func (c *Chunk) Download(URL string, client *http.Client, dest *os.File) (err error) {

req, err := NewRequest("GET", URL)

if err != nil {
return err
}

contentRange := fmt.Sprintf("bytes=%d-%d", c.Start, c.End)

if c.End == 0 {
contentRange = fmt.Sprintf("bytes=%d-", c.Start)
}

req.Header.Set("Range", contentRange)

res, err := client.Do(req)

if err != nil {
return err
}

defer res.Body.Close()

_, err = io.Copy(dest, io.TeeReader(res.Body, c.Progress))
// Reset resets the chunk item to the initial state.
func (c *Chunk) Reset() {
c.Start = 0
c.End = 0
c.Path = ""
c.Done = make(chan struct{})
}

return err
// ChunkPool helps in multi *Download files.
var ChunkPool = &sync.Pool{
New: func() interface{} {
return new(Chunk)
},
}

0 comments on commit 7866184

Please sign in to comment.