Integrate persistence and defensive API boundaries
Integrate persistence and defensive API boundaries
Validate at the HTTP boundary before storing any job. Limit the body with http.MaxBytesReader, require a JSON object with the expected fields, reject trailing JSON and unknown fields, then validate ID and text length. A single-process memory repository can lock the entire compare-and-insert operation. A real durable adapter needs a unique constraint, a transaction or equivalent atomic operation, and a tested recovery contract. The database lesson describes database/sql transactions; here we deliberately avoid claiming a database was tested.
package main
import ( "encoding/json" "fmt" "io" "net/http" "net/http/httptest" "strings")
type Job struct { ID string `json:"id"` Text *string `json:"text"`}
func decode(w http.ResponseWriter, r *http.Request) bool { d := json.NewDecoder(http.MaxBytesReader(w, r.Body, 128)) d.DisallowUnknownFields() var j *Job if d.Decode(&j) != nil || j == nil || j.ID == "" || j.Text == nil { return false } var extra any return d.Decode(&extra) == io.EOF}func main() { for _, s := range []string{`{"id":"a","text":""}`, `{"id":"a"}`, `{"id":"a","text":"x"} {}`, `{"id":"a","text":"x","debug":true}`} { fmt.Println(decode(httptest.NewRecorder(), httptest.NewRequest("POST", "/jobs", strings.NewReader(s)))) }}The pointer distinguishes an explicit empty string from a missing or null text. The snippet illustrates decoding; full validation is in the companion service. Go encoding/json accepts duplicate object keys (later values may replace earlier values), and field matching can be case-insensitive. This lab accepts those decoder semantics; a stricter external contract needs a tokenizer that rejects duplicates and case variants. Never derive paths or SQL from untrusted IDs. Authenticate and authorize before exposing an endpoint to other users; the lab is loopback-only.
Expected output:
truefalsefalsefalseKeep check and insert in one critical section
package main
import ( "fmt" "sync")
type Store struct { mu sync.Mutex m map[string]string}
func (s *Store) put(id, text string) string { s.mu.Lock() defer s.mu.Unlock() if old, ok := s.m[id]; ok { if old != text { return "conflict" } return "reuse" } s.m[id] = text return "create"}func main() { s := Store{m: map[string]string{}} fmt.Println(s.put("a", "Go"), s.put("a", "Go"), s.put("a", "Rust")) fmt.Println(s.m["a"])}The mutex only coordinates this process. Multiple service replicas need shared storage that enforces uniqueness at the storage boundary. Return 413 for a body larger than the HTTP limit, 400 for invalid input, 409 for conflicting replay and 503 for capacity refusal. Do not retry validation errors as transient failures. The companion module contains a bounded in-memory adapter and an explicit durable-adapter handoff checklist; it is not a production persistence implementation.
Expected output:
create reuse conflictGoTry it locally
Use a mutex to protect a map of job IDs with capacity one. Existing IDs must still replay when full; new IDs must be rejected. Check first insert, replay and capacity rejection.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Capstone engineering 04: Integrate persistence and defensive API boundaries
Check the lesson objective before moving on.
Why must compare-and-insert be atomic?
What is the correct response for a different payload under an existing ID?