fetchall exer. complete

This commit is contained in:
Derek McQuay 2015-12-04 15:07:28 -08:00
parent bbefd172c1
commit eb92e7d20c
3 changed files with 149 additions and 0 deletions

48
ch1/dmfetchall/1_10.go Normal file
View File

@ -0,0 +1,48 @@
package main
import (
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"time"
)
func main() {
start := time.Now()
ch := make(chan string)
if len(os.Args[1:]) < 1 {
log.Fatal("needs args")
}
for _, url := range os.Args[1:] {
if !strings.HasPrefix(url, "http://") {
url = "http://" + url
}
go fetch(url, ch)
}
for range os.Args[1:] {
fmt.Println(<-ch)
}
fmt.Printf("%.2fs\n", time.Since(start).Seconds())
main()
}
func fetch(url string, ch chan string) {
start := time.Now()
resp, err := http.Get(url)
if err != nil {
ch <- fmt.Sprint(err)
return
}
defer resp.Body.Close()
nbytes, err := io.Copy(ioutil.Discard, resp.Body)
if err != nil {
ch <- fmt.Sprint(err)
return
}
elapsed := time.Since(start).Seconds()
ch <- fmt.Sprintf("%.2fs %7d %s", elapsed, nbytes, url)
}

54
ch1/dmfetchall/1_11.go Normal file
View File

@ -0,0 +1,54 @@
package main
import (
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"time"
)
func main() {
start := time.Now()
ch := make(chan string)
if len(os.Args[1:]) < 1 {
log.Fatal("needs args")
}
for _, url := range os.Args[1:] {
if !strings.HasPrefix(url, "http://") {
url = "http://" + url
}
go fetch(url, ch)
}
longest := time.After(time.Duration(time.Second))
for range os.Args[1:] {
select {
case s := <-ch:
fmt.Println(s)
case <-longest:
fmt.Println("took too long")
break
}
}
fmt.Printf("%.2fs\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
}
defer resp.Body.Close()
nbytes, err := io.Copy(ioutil.Discard, resp.Body)
if err != nil {
ch <- fmt.Sprint(err)
return
}
elapsed := time.Since(start).Seconds()
ch <- fmt.Sprintf("%.2fs %7d %s", elapsed, nbytes, url)
}

47
ch1/dmfetchall/main.go Normal file
View File

@ -0,0 +1,47 @@
package main
import (
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"time"
)
func main() {
start := time.Now()
ch := make(chan string)
if len(os.Args[1:]) < 1 {
log.Fatal("needs args")
}
for _, url := range os.Args[1:] {
if !strings.HasPrefix(url, "http://") {
url = "http://" + url
}
go fetch(url, ch)
}
for range os.Args[1:] {
fmt.Println(<-ch)
}
fmt.Printf("%.2fs\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
}
defer resp.Body.Close()
nbytes, err := io.Copy(ioutil.Discard, resp.Body)
if err != nil {
ch <- fmt.Sprint(err)
return
}
elapsed := time.Since(start).Seconds()
ch <- fmt.Sprintf("%.2fs %7d %s", elapsed, nbytes, url)
}