package main
import (
"encoding/json"
"fmt"
"net"
"net/http"
"strconv"
"strings"
"sync"
)
type Item struct {
ID int `json:"id"`
Name string `json:"name"`
}
type store struct {
mu sync.Mutex
items map[int]Item
nextID int
}
func writeJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(value)
}
func (s *store) getItem(w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(r.PathValue("id")) // the {id} wildcard from the pattern
if err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "id must be a number"})
return
}
s.mu.Lock()
item, ok := s.items[id]
s.mu.Unlock()
if !ok {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "not found"})
return
}
writeJSON(w, http.StatusOK, item)
}
func (s *store) createItem(w http.ResponseWriter, r *http.Request) {
var input struct {
Name string `json:"name"`
}
r.Body = http.MaxBytesReader(w, r.Body, 64<<10)
if err := json.NewDecoder(r.Body).Decode(&input); err != nil || input.Name == "" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "name is required"})
return
}
s.mu.Lock()
item := Item{ID: s.nextID, Name: input.Name}
s.items[item.ID] = item
s.nextID++
s.mu.Unlock()
writeJSON(w, http.StatusCreated, item)
}
func main() {
s := &store{items: map[int]Item{1: {1, "kettle"}}, nextID: 2}
// Go 1.22+ patterns: an optional method, then a path with {name} wildcards.
mux := http.NewServeMux()
mux.HandleFunc("GET /items/{id}", s.getItem)
mux.HandleFunc("POST /items", s.createItem)
listener, err := net.Listen("tcp", "127.0.0.1:0") // port 0: any free port
if err != nil {
panic(err)
}
defer listener.Close()
go http.Serve(listener, mux)
base := "http://" + listener.Addr().String()
resp, err := http.Post(base+"/items", "application/json", strings.NewReader(`{"name":"mug"}`))
if err != nil {
panic(err)
}
var created Item
json.NewDecoder(resp.Body).Decode(&created)
resp.Body.Close()
if resp.StatusCode != http.StatusCreated || created != (Item{2, "mug"}) {
panic(fmt.Sprint("create failed: ", resp.Status, created))
}
resp, err = http.Get(base + "/items/2")
if err != nil {
panic(err)
}
var fetched Item
json.NewDecoder(resp.Body).Decode(&fetched)
resp.Body.Close()
if fetched != created {
panic(fmt.Sprint("get returned ", fetched))
}
// The mux answers a known path with the wrong method itself: 405 plus an Allow header.
req, _ := http.NewRequest(http.MethodDelete, base+"/items/2", nil)
resp, err = http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusMethodNotAllowed {
panic(resp.Status)
}
fmt.Println("GET /items/2 ->", fetched, "| DELETE ->", resp.StatusCode, "Allow:", resp.Header.Get("Allow"))
}