Start learning free

LESSON 15 OF 173 · BACKEND: YOUR FIRST API

More Routes in Go

Practice

An API has many paths, and each path has its own handler. When a request arrives, Go's router, the ServeMux, compares its path with the pattern of every handler, and calls the handler whose pattern matches. A pattern like "GET /products", with no slash at the end, matches that exact path only. So /products/count is not /products: it needs a handler of its own.

A handler can answer a Go map as JSON: each key of the map becomes a key of the JSON object. For example, a shop could tell its opening hours like this:

app.HandleFunc("GET /hours", func(w http.ResponseWriter, r *http.Request) {
	writeJSON(w, 200, map[string]int{"open": 9, "close": 18})
})

A map's type fixes the type of its values: map[string]int holds whole numbers, map[string]string holds text. To answer how many items a slice has, use len(...) instead of writing the number yourself: the answer stays right when items are added or removed. A path that no pattern matches, like /contact, gets 404 Not Found: Go has no handler to call, so it answers the text 404 page not found.

Your app must answer:

GET /products/count  →  200  {"count": 4}
GET /about           →  200  {"name": "Corner Shop", "currency": "USD"}
GET /contact         →  404  404 page not found
GET /products        →  200  [{"id": 1, "name": "Mug", "price": 12, "category": "kitchen"}, … all 4 products]
GET /                →  200  Welcome to the shop!

Your task: register two handlers. "GET /products/count" answers the number of products as {"count": …}, a map[string]int computed with len(products). "GET /about" answers the shop's "name", "Corner Shop", and its "currency", "USD", as a map[string]string.


Assignment
Follow the Coding Tutorial to add the /products/count and /about handlers.


Hint
Each new handler has the same shape as the others: app.HandleFunc with its pattern, the handler function, and a writeJSON(w, 200, ...) call inside. Put each map inside writeJSON.


STEP 1 OF 4
    Ctrl + Enter to check

    Shop More Routes 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