// Chapter 45 example: decoding JSON strictly, the way a server should. // This program has no server. Each body is what a client might send. // Run with: go run exercises/45/02-strict-decoding.go package main import ( "encoding/json" "errors" "fmt" "io" "strings" ) type itemInput struct { Name string `json:"name"` Quantity int `json:"quantity"` } // decodeInput reads exactly one JSON object with only known fields. func decodeInput(body io.Reader) (itemInput, error) { var input itemInput decoder := json.NewDecoder(body) decoder.DisallowUnknownFields() err := decoder.Decode(&input) if err != nil { return itemInput{}, err } // A second Decode must find nothing at all, or there was extra data. err = decoder.Decode(&struct{}{}) if !errors.Is(err, io.EOF) { return itemInput{}, errors.New("the body must hold one JSON object only") } return input, nil } func main() { bodies := []string{ `{"name": "Rice", "quantity": 2}`, `{"name": "Rice", "quantity": "two"}`, `{"name": "Rice", "colour": "white"}`, `{"name": "Rice"`, ``, `{"name": "Rice"} {"name": "Tea"}`, } for _, body := range bodies { input, err := decodeInput(strings.NewReader(body)) if err != nil { fmt.Println("Error:", err) continue } fmt.Printf("OK: %+v\n", input) } }