Last active
November 14, 2018 12:46
-
-
Save jreisinger/9d504a33f0caa747c354040a36b19df1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io/ioutil" | |
"net/http" | |
"os" | |
) | |
// user-defined type based on struct built-in type | |
type webPage struct { | |
url string | |
body []byte | |
err error | |
} | |
// webPage's method | |
func (w *webPage) get() { | |
resp, err := http.Get(w.url) | |
if err != nil { | |
w.err = err | |
return | |
} | |
defer resp.Body.Close() | |
body, err := ioutil.ReadAll(resp.Body) | |
if err != nil { | |
w.err = err | |
} | |
w.body = body | |
} | |
// wrapper around get() to allow parallelism | |
func getp(w *webPage, ch chan<- string) { | |
w.get() | |
ch <- fmt.Sprintf("url: %s, len: %d, err: %v", w.url, len(w.body), w.err) | |
} | |
func main() { | |
if !(len(os.Args) > 1) { | |
fmt.Fprintf(os.Stderr, "Usage: typesS url [url ...]\n") | |
os.Exit(1) | |
} | |
// create a channel -- communication mechanism that allows one goroutine to | |
// pass values of a specified type to another goroutine | |
ch := make(chan string) | |
// get all urls in parallel | |
for _, url := range os.Args[1:] { | |
w := &webPage{url: url} | |
go getp(w, ch) | |
} | |
// print results in parallel | |
for range os.Args[1:] { | |
fmt.Println(<-ch) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment