// Homework 46, problem 3: Many searches at once. // // Start the Chapter 45 items server first, in another terminal: // cd exercises/45/03-items-api // go run . // Write searchURL, which builds server + /api/items?q=WORDS with url.Values, // and countMatches, which asks that address and returns how many items came // back. Then change main so that the searches run at the same time, one // goroutine each, with a sync.WaitGroup. // // Run with: go run exercises/46/homework/03-many-searches.go package main import ( "context" "errors" "flag" "fmt" "net/http" "time" ) type item struct { ID int `json:"id"` Name string `json:"name"` } // searchURL returns server + /api/items?q=words, with words encoded. func searchURL(server string, words string) (string, error) { // TODO: write your code here, in place of this placeholder line: return "", errors.New("TODO: searchURL is not written yet") } // countMatches asks for address, and returns the number of items in the reply. func countMatches(ctx context.Context, client *http.Client, address string) (int, error) { // TODO: write your code here, in place of this placeholder line: return 0, errors.New("TODO: countMatches is not written yet") } // searchOne builds the address for words and counts the items that match. func searchOne(ctx context.Context, client *http.Client, server string, words string) (int, error) { address, err := searchURL(server, words) if err != nil { return 0, err } return countMatches(ctx, client, address) } func main() { server := flag.String("server", "http://localhost:8080", "address of the items server") flag.Parse() words := []string{"rice", "tea", "green tea", "salt & pepper", "SOAP"} client := &http.Client{Timeout: 10 * time.Second} ctx := context.Background() counts := make([]int, len(words)) errs := make([]error, len(words)) // TODO: run the searches at the same time, one goroutine each, with a // sync.WaitGroup. This loop runs them one after another. for i, word := range words { counts[i], errs[i] = searchOne(ctx, client, *server, word) } for i, word := range words { if errs[i] != nil { fmt.Printf("%-15q error: %v\n", word, errs[i]) continue } fmt.Printf("%-15q %d found\n", word, counts[i]) } }