Start learning free

LESSON 30 OF 173 · BACKEND: YOUR FIRST API

Only the First Few in Go

Practice

A real shop can have thousands of products, and a page often shows only a few. A client asks for that with a query parameter: ?limit=2 means "at most 2 products".

To keep the first few items of a slice, use a slice expression. items[:n] goes from the start up to, but not including, position n. Go is strict about it: if n is past the end of the slice, or negative, the program panics with "slice bounds out of range". The built-in min keeps n at most the length:

days := []string{"Mon", "Tue", "Wed", "Thu", "Fri"}
fmt.Println(days[:2])                    // [Mon Tue]
fmt.Println(days[:min(10, len(days))])   // [Mon Tue Wed Thu Fri]
// days[:10] would panic: slice bounds out of range

Cut the list last, after filtering and sorting, so ?sort=price&limit=2 gives the two cheapest products. A limit of 0 or less makes no sense, so it gets 400. Without limit, strconv.Atoi gets the empty string and returns an error: then there is nothing to check or cut, and the answer is the whole list, as before. The lists below show product names only.

GET /products?limit=2  →  200  [Mug, Notebook]
GET /products?sort=price&limit=2  →  200  [Pen, Notebook]
GET /products?category=office&limit=1  →  200  [Notebook]
GET /products?limit=10  →  200  [Mug, Notebook, Lamp, Pen]
GET /products?limit=0  →  400  {"error": "Limit must be 1 or more"}
GET /products?limit=-3  →  400  {"error": "Limit must be 1 or more"}

Your task: in GET /products, read limit as a whole number, answer 400 when it is less than 1, and cut the list to its first limit products.


Assignment
Follow the Coding Tutorial to add a limit to GET /products.


Hint
Read limit with strconv.Atoi, like maxPrice, but name its error limitErr. Check it before the loop only when limitErr is nil, and cut result just before writeJSON, after the sorting.


STEP 1 OF 5
    Ctrl + Enter to check

    Shop Limit 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