Start learning free

LESSON 27 OF 173 · BACKEND: YOUR FIRST API

JSON for Unknown Paths in Go

Practice

Your handlers send errors as JSON. But when a request matches no pattern at all, like GET /contact, none of your code runs: Go's ServeMux answers by itself, with 404 and the plain text 404 page not found. A browser can show it, but a program that expects JSON can't read it.

The fix is a catch-all handler. A pattern that ends in / matches every path below it, and the mux always picks the most specific pattern that matches, so a short pattern only gets the requests no other pattern takes. Here is one for everything under /admin/ (not part of this lesson):

app.HandleFunc("/admin/", func(w http.ResponseWriter, r *http.Request) {
	errorResponse(w, "Admins only", 403)
})

The pattern "/" with no method in front is below every path and matches every method. So it also takes a known path with a method no pattern has: DELETE /products gets your JSON 404 instead of Go's 405. A handler that sends its own 404, like the one for GET /products/{id}, keeps its own message. And {id} matches any text, so /products/abc reaches that handler: when strconv.Atoi fails, it should give the same JSON 404. The requests and answers your code must give, in this order:

GET /contact  →  404  {"error": "Not found"}
GET /products/abc  →  404  {"error": "Not found"}
POST /orders  {"product_id": 1, "quantity": 2}  →  404  {"error": "Not found"}
GET /products/9  →  404  {"error": "Product not found"}
DELETE /products  →  404  {"error": "Not found"}
GET /about  →  200  {"name": "Corner Shop", "currency": "USD"}

Your task: register a handler for the pattern "/" that answers {"error": "Not found"} with status 404 through your errorResponse helper, and give the same answer in the GET /products/{id} handler when the id isn't a number.


Assignment
Follow the Coding Tutorial to add a catch-all handler that answers unknown paths in JSON.


Hint
Write "/" with no method in front: "GET /" would only catch GET requests. The order you register patterns in doesn't matter, because the most specific match wins, so GET /products/9 keeps its own message.


STEP 1 OF 3
    Ctrl + Enter to check

    Shop Json 404 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