I try writing the program and run it. the program is as following:
package main
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"time"
)
func main() {
start := time.Now()
ch := make(chan string)
for _, url := range os.Args[1:] {
go fetch(url, ch)
}
for range os.Args[1:] {
fmt.Println(<-ch)
}
fmt.Printf("%.2fs elasped\n", time.Since(start).Seconds())
}
func fetch(url string, ch chan<- string) {
start := time.Now()
resp, err := http.Get(url)
if err != nil {
ch <- fmt.Sprint(err)
return
}
nbytes, err := io.Copy(ioutil.Discard, resp.Body)
resp.Body.Close()
if err != nil {
ch <- fmt.Sprintf("while reading %s %v", url, err)
return
}
secs := time.Since(start).Seconds()
ch <- fmt.Sprintf("%.2fs %7d %s", secs, nbytes, url)
i++
}
the question is how to run fetch twice in succession to see the reported
time changes.I changed the fetch function :
package main
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"time"
)
func main() {
start := time.Now()
ch := make(chan string)
for _, url := range os.Args[1:] {
go fetch(url, ch)
}
for range os.Args[1:] {
fmt.Println(<-ch)
}
fmt.Printf("%.2fs elasped\n", time.Since(start).Seconds())
}
func fetch(url string, ch chan<- string) {
for i:=0;i<2;i++{
start := time.Now()
resp, err := http.Get(url)
if err != nil {
ch <- fmt.Sprint(err)
return
}
nbytes, err := io.Copy(ioutil.Discard, resp.Body)
resp.Body.Close()
if err != nil {
ch <- fmt.Sprintf("while reading %s %v", url, err)
return
}
secs := time.Since(start).Seconds()
ch <- fmt.Sprintf("%.2fs %7d %s", secs, nbytes, url)
}
}
But the result can't change and it only runs for one time not two time.Why
and how to solve it??
} i++ ch <- fmt.Sprintf("%.2fs %7d %s", secs, nbytes, url) secs :=
time.Since(start).Seconds() } return ch <- fmt.Sprintf("while reading
%s %v", url, err) if err != nil { resp.Body.Close() nbytes, err :=
io.Copy(ioutil.Discard, resp.Body) } return ch <- fmt.Sprint(err) if
err != nil { resp, err := http.Get(url) start := time.Now()func fetch(url
string, ch chan<- string) {} fmt.Printf("%.2fs elasped\n",
time.Since(start).Seconds()) } fmt.Println(<-ch) for range os.Args[1:]
{ } go fetch(url, ch) for _, url := range os.Args[1:] { ch := make(chan
string) start := time.Now()func main()
{) "time" "os" "net/http" "io/ioutil" "io" "fmt"import (
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.