A long list is rarely sent in one answer. APIs split it into pages: each answer holds a few items and says which page comes next. You keep asking until there is no next page.
You don't know in advance how many pages there are, so use a for loop with only a condition, Go's while loop. On the last page next_page is null, and decoding null into an int field leaves it at its zero value, 0: stop when the page is 0. Here is the same idea on a plain map, following a chain of bus stops (a missing key gives ""):
nextStop := map[string]string{"Home": "Park", "Park": "School"}
stop := "Home"
for stop != "" {
fmt.Println(stop)
stop = nextStop[stop]
}
The supplier's /catalog has 5 products, 2 per page:
GET /catalog?page=1 → {"page": 1, "items": ["Mug", "Notebook"], "next_page": 2}
GET /catalog?page=2 → {"page": 2, "items": ["Lamp", "Pen"], "next_page": 3}
GET /catalog?page=3 → {"page": 3, "items": ["Plant"], "next_page": null}
Your program must print:
Page 1 Mug Notebook Page 2 Lamp Pen Page 3 Plant
Your task: the Catalog struct is given. Start at page 1 and keep asking /catalog for the page that next_page names, until it is 0. For each page, print Page and its number, then every product name on it.
Assignment
Follow the Coding Tutorial to read every page of the catalog and print all its products.
Hint
Build the URL with "/catalog?page=" + strconv.Itoa(page). Set page to data.NextPage as the last line of the loop, or the program will ask for page 1 forever.
Free plan: 30 tutor messages. PRO is unlimited.
