Start learning free

LESSON 12 OF 173 · BACKEND: HOW THE WEB WORKS

Project: A Restock Report in Go

Practice

This project puts the whole module together. The shop wants a restock report: every product the supplier has fewer than 10 of, with its stock and its price, sorted by name. No single answer has all of that. /prices has the names and prices, and /stock has the counts, but only if you send the X-Api-Key header.

Joining two answers: both lists use the same id for a product, and that is the only thing that links them. Turn the stock list into a map from each id to its count. Then stock[product.ID] gives any product's stock in one step, with no searching.

Sorting structs: Go can't tell on its own which field of a struct decides the order. sort.Slice takes the slice and a function that gets two positions, i and j, and returns true when the item at i should come first. For example, to sort a cart by price:

sort.Slice(cart, func(i, j int) bool {
    return cart[i].Price < cart[j].Price
})

sort.Slice calls your function on many pairs and moves the items for you. Your program must print exactly these lines:

Lamp: 8 left, price 14
Notebook: 0 left, price 3
Plant: 0 left, price 6

Your task: supplier, apiKey, the Product struct and the /prices request are given. Decode /prices, read /stock with the key, build the map stock from id to count, then print every product with fewer than 10 left, sorted by name: its name with a colon, its stock, left, price and its price.


Assignment
Follow the Coding Tutorial to build the restock report: two requests, a map of stock by id, the printing loop and a sort by name.


Hint
Build stock before the loop, starting from an empty map[int]int{}. In the loop, compare stock[product.ID] with 10 using <. Call sort.Slice just before the product loop, comparing prices[i].Name with prices[j].Name.


STEP 1 OF 12
    Ctrl + Enter to check

    Web Restock Report in Go

    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free