// Chapter 46 example: building a URL with a query safely, using net/url. // Start the Chapter 45 server first, in another terminal. // Run with: go run exercises/46/02-search.go green tea package main import ( "context" "encoding/json" "flag" "fmt" "net/http" "net/url" "os" "strings" "time" ) type item struct { ID int `json:"id"` Name string `json:"name"` } // searchURL returns server + /api/items?q=search, with the search encoded. func searchURL(server string, search string) (string, error) { u, err := url.Parse(server) if err != nil { return "", fmt.Errorf("the server address %q is not valid: %w", server, err) } u = u.JoinPath("api", "items") query := url.Values{} query.Set("q", search) u.RawQuery = query.Encode() return u.String(), nil } func search(ctx context.Context, client *http.Client, address string) ([]item, error) { request, err := http.NewRequestWithContext(ctx, "GET", address, nil) if err != nil { return nil, fmt.Errorf("search: %w", err) } response, err := client.Do(request) if err != nil { return nil, fmt.Errorf("search: %w", err) } defer response.Body.Close() if response.StatusCode != http.StatusOK { return nil, fmt.Errorf("search: the server replied %s", response.Status) } var items []item err = json.NewDecoder(response.Body).Decode(&items) if err != nil { return nil, fmt.Errorf("search: %w", err) } return items, nil } func main() { server := flag.String("server", "http://localhost:8080", "address of the items server") flag.Parse() words := strings.Join(flag.Args(), " ") if words == "" { fmt.Fprintln(os.Stderr, "Usage: go run exercises/46/02-search.go [-server URL] WORDS") os.Exit(2) } address, err := searchURL(*server, words) if err != nil { fmt.Fprintln(os.Stderr, "Error:", err) os.Exit(1) } fmt.Println("Asking for", address) client := &http.Client{Timeout: 10 * time.Second} items, err := search(context.Background(), client, address) if err != nil { fmt.Fprintln(os.Stderr, "Error:", err) os.Exit(1) } if len(items) == 0 { fmt.Println("Nothing found.") return } for _, it := range items { fmt.Printf("%d: %s\n", it.ID, it.Name) } }