Hi guys,
I'm working on writing an exercise of concurrently downloading a file (from HTTP file server) using go routine. However I got stuck when debugging channel code.
Could you please help me take a look and see where I made wrong? Thank you in advance.
Code:
package main
import (
"fmt"
"os"
"net/http"
"io/ioutil"
"strconv"
"bytes"
)
func downRange(ran, url string, data chan *[]byte) {
fmt.Println("Downloading range: " + ran)
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Range", "bytes= " + ran)
// fmt.Println(req.Header)
client := &http.Client{}
resp, err1:= client.Do(req)
if err1 != nil {
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusPartialContent {
fmt.Println(resp.StatusCode)
fmt.Println("File server does not support range download.")
}
data2, _ := ioutil.ReadAll(resp.Body)
fmt.Println("before")
data <- &data2
fmt.Println("after")
}
func getFileSize(url string) (size int64, err error) {
req, _ := http.NewRequest("GET", url, nil)
client := &http.Client{}
resp, err1:= client.Do(req)
if err1 != nil {
err = err1
return
}
//defer resp.Body.Close()
fmt.Println(resp.ContentLength)
return resp.ContentLength, err
}
func genRanges(num int, total int64) (ranges *[]string) {
single := total / int64(num)
//fmt.Println(single)
myranges := make([]string, num)
for i:=0; i<num-1; i++ {
myranges[i] = strconv.FormatInt(int64(i)*single, 10) + "-" + strconv.FormatInt(int64(i+1)*single-1, 10)
//fmt.Println(myranges[i])
}
myranges[num-1] = strconv.FormatInt(int64(num-1)*single, 10) + "-"
return &myranges
}
func main() {
url := "
http://localhost:8080/Test.zip"
num := 10
total, _ := getFileSize(url)
myranges := genRanges(num, total)
single := total / int64(num)
data := make([][]byte, num)
// fmt.Println(*myranges)
for i, ran := range *myranges {
var mydata chan *[]byte
data[i] = make([]byte, single)
var err error = nil
go downRange(ran, url, mydata)
mynewdata := <- mydata
copy(data[i], *mynewdata)
fmt.Println(data[i])
if err != nil {
fmt.Println(err)
}
}
perm := os.ModePerm
fulldata := bytes.Join(data, nil)
ioutil.WriteFile("C:/a.zip", fulldata, perm)
fmt.Println("Download successful.")
}
Running Results:
C:\works\go>go run download2.go
7360368
Downloading range: 0-736035
before
_
It stuck at right after before. I have no idea what happened, maybe I still does not understand how it works for go routine and channel.
Could anyone help me explain a little bit on the above issue, why it stuck at right after "before" was printed.
Thank you in advance.