Validate DTOs and domain invariants
Validate DTOs and domain invariants
Validate at two boundaries: parsing checks the request representation, and domain validation checks whether the proposed operation is allowed. A quantity may be valid JSON and still violate a business rule. Limit bytes before decoding; reject unsupported fields and trailing values if the contract requires one object. Choose documented status codes consistently.
package main
import ( "encoding/json" "errors" "fmt" "io" "net/http" "net/http/httptest" "strings")
type Order struct { Quantity int `json:"quantity"`}
func readOrder(w http.ResponseWriter, r *http.Request) int { r.Body = http.MaxBytesReader(w, r.Body, 64) defer r.Body.Close() d := json.NewDecoder(r.Body) d.DisallowUnknownFields() var o Order if e := d.Decode(&o); e != nil { var big *http.MaxBytesError if errors.As(e, &big) { return 413 } return 400 } if e := d.Decode(new(any)); e != io.EOF { var big *http.MaxBytesError if errors.As(e, &big) { return 413 } return 400 } if o.Quantity < 1 || o.Quantity > 10 { return 422 } return 201}func main() { for _, s := range []string{`{"quantity":2}`, `{"quantity":0}`, `{"quantity":2,"x":1}`, `{"quantity":2}{}`, strings.Repeat(" ", 65)} { fmt.Println(readOrder(httptest.NewRecorder(), httptest.NewRequest("POST", "/", strings.NewReader(s)))) }}This parser rejects unknown fields, extra JSON values and oversized bodies; 422 denotes a syntactically valid but unacceptable quantity. 201 is a simulated success status, not proof of persistence. DisallowUnknownFields is not a full schema validator: duplicate keys and case-insensitive matches need extra policy. A real endpoint also checks Content-Type and authentication.
Expected output:
201422400400413Protect the invariant inside the mutation
package main
import ( "fmt" "sync")
type Stock struct { mu sync.Mutex left int}
func (s *Stock) reserve(n int) bool { s.mu.Lock() defer s.mu.Unlock() if n <= 0 || n > s.left { return false } s.left -= n return true}func main() { s := Stock{left: 3} fmt.Println(s.reserve(2), s.reserve(2), s.left)}An inventory check and decrement happen under the same lock. Checking outside the mutation can let two concurrent orders overbook. Across processes use a database transaction or another atomic persistence mechanism; a Go mutex cannot coordinate different servers.
Expected output:
true false 1Try it locally
Using readOrder, test quantity 10, quantity 11 and a string instead of an integer. Print 201, 422 and 400 on separate lines.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
REST API 03: Validate DTOs and domain invariants
Check the lesson objective before moving on.
Why check stock inside a lock?
What is DisallowUnknownFields not sufficient to enforce?