Gin project: a complete REST API · 5 MIN READ
Full CRUD on one resource: exact status codes, a Location header and PUT versus PATCH
Implement create, read, replace, patch and delete for notes with correct status codes, a Location header and presence-aware PATCH fields.
CRUD looks like boilerplate until a client depends on the details: whether create tells it where the new note lives, whether PUT without a body field clears it, whether PATCH with false can unpin a note, and whether a duplicate title is a 400 or a 409. This lesson pins down each answer for the notes resource, on top of a mutex-protected in-memory store behind the Store interface.
gin · A MAP OF THE IDEA
- Write the route contract
- Guard invariants in store
- Bind PUT and PATCH apart
- Test every status row
Useful when
- Clients can rely on Location, 204 and 409 meaning the same thing everywhere.
- Uniqueness is enforced where the data lives, so no check-then-write race.
- PATCH can set false and empty values without ambiguity.
Watch out
- Pointer DTOs cannot distinguish an omitted field from an explicit null.
- A store-level lock does not prevent lost updates between two clients.
Implementation & operation cost: Two DTOs per resource and an Update callback in the store; worth it as soon as a client sends partial updates.
Write the contract before the handlers
A resource API is a promise about methods, paths, statuses and headers, and clients code against every part of it. Writing the table first exposes decisions that are easy to fudge in code: who assigns IDs, what a partial update means and which errors exist. Here the server assigns IDs, so POST creates and PUT only replaces an existing note. Titles are unique, which gives the store a real invariant to protect and the API a real reason to answer 409.
POST /notes create 201 Created + Location: /notes/{id} + body
400 unreadable body, 409 title already used
GET /notes/{id} read 200 + body, 404 unknown id
PUT /notes/{id} replace 200 + body, 400 incomplete body, 404, 409
PATCH /notes/{id} merge 200 + body, 400 invalid field, 404, 409
DELETE /notes/{id} remove 204 No Content (empty body), 404 unknown idRead each row as a test case. 201 always comes with a Location header pointing at the new resource, so clients never guess URLs. 204 means success with no body: the net/http server rejects a body write for it with http.ErrBodyNotAllowed, and Gin renderers skip the body for that status. 404 and 409 come from domain errors, not from handler logic. 400 is for input the adapter cannot accept; the binding-limits lesson already covers size limits and strict decoding, so this lesson only uses binding tags.
Five routes over one locked store
The store keeps two maps that must always agree: notes by ID and a unique index from title to ID. Every method takes the mutex, and Update runs a caller-supplied function on a copy while holding the write lock, so read, modify and write happen as one step. Handlers translate HTTP into store calls and use a small writeError helper for now. The program replays a short session against the API and prints each status, Location header and body.
package main
import (
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync"
"github.com/gin-gonic/gin"
)
// ---- internal/notes ----
type Note struct {
ID string `json:"id"`
Title string `json:"title"`
Body string `json:"body"`
Pinned bool `json:"pinned"`
}
var (
ErrNotFound = errors.New("notes: not found")
ErrConflict = errors.New("notes: title already used")
)
type Store interface {
Create(ctx context.Context, n Note) error
Get(ctx context.Context, id string) (Note, error)
// Update runs fn on a copy under the store's lock and saves the result.
Update(ctx context.Context, id string, fn func(*Note) error) (Note, error)
Delete(ctx context.Context, id string) error
}
// ---- internal/store ----
type MemoryStore struct {
mu sync.RWMutex
byID map[string]Note
byTitle map[string]string // unique index: title -> id
}
func NewMemoryStore() *MemoryStore {
return &MemoryStore{byID: map[string]Note{}, byTitle: map[string]string{}}
}
func (m *MemoryStore) Create(_ context.Context, n Note) error {
m.mu.Lock()
defer m.mu.Unlock()
if _, taken := m.byTitle[n.Title]; taken {
return ErrConflict
}
m.byID[n.ID] = n
m.byTitle[n.Title] = n.ID
return nil
}
func (m *MemoryStore) Get(_ context.Context, id string) (Note, error) {
m.mu.RLock()
defer m.mu.RUnlock()
n, ok := m.byID[id]
if !ok {
return Note{}, ErrNotFound
}
return n, nil // a copy: callers cannot mutate the map behind the lock
}
func (m *MemoryStore) Update(_ context.Context, id string, fn func(*Note) error) (Note, error) {
m.mu.Lock()
defer m.mu.Unlock()
old, ok := m.byID[id]
if !ok {
return Note{}, ErrNotFound
}
next := old
if err := fn(&next); err != nil {
return Note{}, err
}
next.ID = old.ID // the URL owns the identity, not the body
if owner, taken := m.byTitle[next.Title]; taken && owner != id {
return Note{}, ErrConflict
}
delete(m.byTitle, old.Title)
m.byTitle[next.Title] = id
m.byID[id] = next
return next, nil
}
func (m *MemoryStore) Delete(_ context.Context, id string) error {
m.mu.Lock()
defer m.mu.Unlock()
n, ok := m.byID[id]
if !ok {
return ErrNotFound
}
delete(m.byTitle, n.Title)
delete(m.byID, id)
return nil
}
// ---- internal/httpapi ----
type Handler struct {
store Store
nextID func() string
}
func (h *Handler) Register(r gin.IRouter) {
r.POST("/notes", h.create)
r.GET("/notes/:id", h.get)
r.PUT("/notes/:id", h.replace)
r.PATCH("/notes/:id", h.patch)
r.DELETE("/notes/:id", h.remove)
}
// putNote is a full representation: an absent field means its zero value.
type putNote struct {
Title string `json:"title" binding:"required,max=80"`
Body string `json:"body" binding:"max=2000"`
Pinned bool `json:"pinned"`
}
// patchNote uses pointers: nil means "not sent", so false and "" stay expressible.
type patchNote struct {
Title *string `json:"title" binding:"omitempty,min=1,max=80"`
Body *string `json:"body" binding:"omitempty,max=2000"`
Pinned *bool `json:"pinned"`
}
func (h *Handler) create(c *gin.Context) {
var in putNote
if err := c.ShouldBindJSON(&in); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid note"})
return
}
n := Note{ID: h.nextID(), Title: in.Title, Body: in.Body, Pinned: in.Pinned}
if err := h.store.Create(c.Request.Context(), n); err != nil {
writeError(c, err)
return
}
c.Header("Location", "/notes/"+n.ID)
c.JSON(http.StatusCreated, n)
}
func (h *Handler) get(c *gin.Context) {
n, err := h.store.Get(c.Request.Context(), c.Param("id"))
if err != nil {
writeError(c, err)
return
}
c.JSON(http.StatusOK, n)
}
func (h *Handler) replace(c *gin.Context) {
var in putNote
if err := c.ShouldBindJSON(&in); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid note"})
return
}
n, err := h.store.Update(c.Request.Context(), c.Param("id"), func(n *Note) error {
n.Title, n.Body, n.Pinned = in.Title, in.Body, in.Pinned
return nil
})
if err != nil {
writeError(c, err)
return
}
c.JSON(http.StatusOK, n)
}
func (h *Handler) patch(c *gin.Context) {
var in patchNote
if err := c.ShouldBindJSON(&in); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid patch"})
return
}
n, err := h.store.Update(c.Request.Context(), c.Param("id"), func(n *Note) error {
if in.Title != nil {
n.Title = *in.Title
}
if in.Body != nil {
n.Body = *in.Body
}
if in.Pinned != nil {
n.Pinned = *in.Pinned
}
return nil
})
if err != nil {
writeError(c, err)
return
}
c.JSON(http.StatusOK, n)
}
func (h *Handler) remove(c *gin.Context) {
if err := h.store.Delete(c.Request.Context(), c.Param("id")); err != nil {
writeError(c, err)
return
}
c.Status(http.StatusNoContent)
}
// writeError is a stopgap; the problem-details lesson moves this into one middleware.
func writeError(c *gin.Context, err error) {
switch {
case errors.Is(err, ErrNotFound):
c.JSON(http.StatusNotFound, gin.H{"error": "note not found"})
case errors.Is(err, ErrConflict):
c.JSON(http.StatusConflict, gin.H{"error": "title already used"})
default:
c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
}
}
func main() {
gin.SetMode(gin.TestMode)
seq := 0
h := &Handler{store: NewMemoryStore(), nextID: func() string { seq++; return fmt.Sprintf("n%d", seq) }}
r := gin.New()
h.Register(r)
steps := []struct{ method, path, body string }{
{"POST", "/notes", `{"title":"Groceries","body":"milk, eggs"}`},
{"POST", "/notes", `{"title":"Groceries"}`},
{"PATCH", "/notes/n1", `{"pinned":true}`},
{"PUT", "/notes/n1", `{"title":"Groceries"}`},
{"POST", "/notes", `{"title":"Errands"}`},
{"PATCH", "/notes/n3", `{"title":""}`},
{"PATCH", "/notes/n3", `{"title":"Groceries"}`},
{"DELETE", "/notes/n1", ""},
{"GET", "/notes/n1", ""},
}
for _, s := range steps {
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(s.method, s.path, strings.NewReader(s.body)))
line := fmt.Sprintf("%s %s -> %d", s.method, s.path, w.Code)
if loc := w.Header().Get("Location"); loc != "" {
line += " Location: " + loc
}
if w.Body.Len() > 0 {
line += " " + w.Body.String()
}
fmt.Println(line)
}
}The first POST returns 201 with Location: /notes/n1. The duplicate POST gets 409 from the unique index; it still consumed ID n2 because the handler allocates the ID before inserting, just as a database sequence would, so the next note is n3. PATCH with {"pinned":true} changes one field and keeps the body. PUT with only a title replaces the whole representation, so body becomes "" and pinned becomes false. PATCH with an empty title is rejected with 400 because the field is present and fails min=1. Renaming n3 to an existing title is 409. DELETE answers 204 with no body, and the following GET is 404.
PUT replaces, PATCH merges, pointers carry presence
putNote has plain fields because PUT sends a complete representation: anything absent takes its zero value, and title is required. patchNote uses pointers because PATCH must tell "not sent" from "set to the zero value"; with a plain bool, {"pinned":false} and {} decode identically. Validator tags cooperate with this: omitempty on a pointer skips only a nil pointer, so a present empty string is still checked against min=1, which is the 400 in the output. One limit remains: JSON null also leaves a pointer nil, so this DTO cannot express "clear this field" the way JSON Merge Patch (RFC 7396) does, where null removes a member. If clients need that, decode into map[string]json.RawMessage or a small optional type that records both presence and null. Whichever you choose, document it and accept application/merge-patch+json if you claim merge-patch semantics.
What the lock protects, and what it cannot
The mutex protects an invariant, not just a map: byID and byTitle change together or not at all. That is why the uniqueness check lives inside Create and Update rather than in a handler that first asks "is this title free?" and then writes; between those two calls another request could take the title. In PostgreSQL the same guarantee comes from a unique index, and the adapter maps SQLSTATE 23505 (unique_violation) to notes.ErrConflict. Get returns a copy of the struct, so callers cannot mutate stored state behind the lock; a Note with slice fields would need a deep copy. The function passed to Update runs under the write lock, so it must be quick and free of I/O. What the lock cannot fix is two clients that each read version one and write back their own edit; that lost update spans two requests and is the subject of the optimistic-concurrency lesson.
Status-code questions reviewers ask
Should POST return 200? No: 201 plus Location tells the client a new resource exists and where. Can Location be relative? Yes, RFC 9110 allows a URI reference, resolved against the request URL. Is a second DELETE returning 404 a violation of idempotency? No: idempotency is about the effect on server state, which is the same after one or two deletes; the responses may differ. Should PUT to an unknown ID create it? Only when clients choose IDs; then it returns 201. Is a duplicate title 400 or 409? The request is well formed but conflicts with current state, so 409. Never answer 200 with an error object in the body. Test each row of the contract through ServeHTTP, including the Location header and the empty 204 body.
TAKE THIS WITH YOU
Return 201 with Location on create and 204 with no body on delete, derive 404 and 409 from domain errors, treat PUT as full replacement and give PATCH presence-aware pointer fields.
Check your understanding
A PATCH request sends {"pinned":false}. Why does patchNote use *bool instead of bool for Pinned?
Go to the source
Progress stays in this browser. No account needed.