Start learning free

LESSON 25 OF 173 · BACKEND: YOUR FIRST API

Methods a Path Allows in Go

Practice

Each handler answers one method on one path. When a request comes for a path that exists, but with a method no handler is registered for, Go's ServeMux answers 405 Method Not Allowed. With it, it sends an Allow header: the list of methods the path does accept. A path with no handler at all still gets 404 Not Found, with the text 404 page not found.

For example, / has only the pattern "GET /{$}", so DELETE / gets 405 with Allow: GET, HEAD. Go adds HEAD by itself wherever a path has GET. You never write code for a 405: to allow a method on a path, you register a handler for it.

That's what you'll do for /about. Its answer used to be written inside the handler, so nothing could change it. You'll keep the shop's details in a package-level map shop that both handlers share, and add a PUT handler that replaces them. The requests and answers your code must give, in this order:

PUT /products  {"name": "Cup", "price": 5, "category": "kitchen"}
  →  405  Allow: GET, HEAD, POST
POST /products/2  {"price": 5}
  →  405  Allow: DELETE, GET, HEAD, PATCH, PUT
DELETE /about  →  405  Allow: GET, HEAD, PUT
PUT /about  {"name": "Corner Store", "currency": "EUR"}
  →  200  {"name": "Corner Store", "currency": "EUR"}
GET /about  →  200  {"name": "Corner Store", "currency": "EUR"}
GET /contact  →  404  404 page not found

Your task: keep the about details in a map shop, make GET /about answer it, and add a handler for PUT /about, which replaces the name and currency with the ones in the body and answers the new details. Then /about allows GET and PUT.


Assignment
Follow the Coding Tutorial to store the shop's details in a variable and add a PUT handler for /about.


Hint
shop lives outside newApp, so both handlers read and change the same map. The 405 answers need no code: Go's ServeMux sends them, with the Allow header, for every method a path has no handler for.


STEP 1 OF 8
    Ctrl + Enter to check

    Shop Method Not Allowed 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