Skip to content

Instantly share code, notes, and snippets.

@alash3al
Last active January 4, 2016 10:56
Show Gist options
  • Save alash3al/c884b3e61806e3faaa03 to your computer and use it in GitHub Desktop.
Save alash3al/c884b3e61806e3faaa03 to your computer and use it in GitHub Desktop.
just for fun ;), i'm "www.alash3al.xyz"
package main
import(
"fmt"
"net/http"
"os"
"sync"
"io"
)
func request(method, url string, headers map[string]string) (*http.Response, error) {
client := &http.Client{}
defer func(){client = nil}()
req, err := http.NewRequest(method, url, nil)
if err != nil {return nil, err}
for k, v := range headers {req.Header.Set(k, v)}
return client.Do(req)
}
func main() {
url := `https://storage.googleapis.com/golang/go1.5.1.windows-386.msi`
//end := make(chan bool)
done := uint64(0)
max := 61
info, _ := request("HEAD", url, nil)
chunk := uint64(info.ContentLength)/uint64(max)
wg := &sync.WaitGroup{}
wg.Add(max)
for i := 0; i < max; i++ {
go (func(i int, done uint64, wg *sync.WaitGroup){
from := uint64(i) * chunk
to := (from + chunk) - uint64(1)
fd, _ := os.OpenFile(fmt.Sprintf(`./tmp/tmp-%d.tmp`, i), os.O_WRONLY|os.O_CREATE, 0777)
data, err := request("GET", url, map[string]string{
`Range`: fmt.Sprintf(`bytes=%d-%d`, from, to),
})
if err != nil {
return
}
fmt.Printf(`Worker(%d) Downloading from %d to %d` + "\n", i, from, to)
defer fd.Close()
defer data.Body.Close()
defer wg.Done()
defer (func(){
*&done += uint64(data.ContentLength)
fmt.Printf(`Worker(%d) Finished` + "\n", i)
})()
io.Copy(fd, data.Body)
})(i, done, wg)
}
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment