Skip to content

Instantly share code, notes, and snippets.

@ivanmrchk
Created September 20, 2019 11:37
Show Gist options
  • Save ivanmrchk/b4f4c6ab2ac3ac8c1e1378c8d20db13a to your computer and use it in GitHub Desktop.
Save ivanmrchk/b4f4c6ab2ac3ac8c1e1378c8d20db13a to your computer and use it in GitHub Desktop.
Count "Go" occurrences
package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"sync"
)
func main() {
total := 0
// Read from Stdin
buf := new(bytes.Buffer)
buf.ReadFrom(os.Stdin)
// Convert to string and split urls
s := buf.String()
urls := strings.Split(s, "\n")
// strip the last element off of the slice
urls = urls[:len(urls)-1]
var wg sync.WaitGroup
wg.Add(len(urls))
for _, url := range urls {
go func(url string) {
defer wg.Done()
// do the get requests
resp, err := http.Get(strings.TrimSpace(url))
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
// read the resp body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
// count "Go" occurencies
result := strings.Count(string(body), "Go")
total += result
fmt.Println("Count for "+url+": ", result)
}(url)
}
wg.Wait()
fmt.Println("Total: ", total)
}
//echo -e 'https://golang.org\nhttps://golang.org' | go run main.go
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment