package modules import ( "bytes" "encoding/json" "errors" "fmt" "io" "maps" "reflect" "slices" "strconv" "strings" ) // maxNameInProblem caps how much of an unknown field's name a problem // repeats. const maxNameInProblem = 64 // DecodeStrict decodes body, which must be one JSON object, into the struct // v points to. A name must match a field's json tag exactly, so a name in // another case is unknown. Every problem is reported at once, in a // *PayloadError: a body that is not one JSON object, each unknown field and // each field of the wrong type. A field that is null counts as absent. func DecodeStrict(body []byte, v any) error { rv := reflect.ValueOf(v) if rv.Kind() != reflect.Pointer || rv.Elem().Kind() != reflect.Struct { panic("modules.DecodeStrict: v must point to a struct") } var object map[string]json.RawMessage dec := json.NewDecoder(bytes.NewReader(body)) if err := dec.Decode(&object); err != nil { return &PayloadError{Problems: []string{bodyProblem(err)}} } if object == nil { return &PayloadError{Problems: []string{"body: expected a JSON object, got null"}} } if _, err := dec.Token(); !errors.Is(err, io.EOF) { return &PayloadError{Problems: []string{"body: trailing data after the payload"}} } target := rv.Elem() fields := jsonFields(target.Type()) var problems []string for _, name := range slices.Sorted(maps.Keys(object)) { index, ok := fields[name] if !ok { problems = append(problems, fieldName(name)+": unknown field") continue } field := target.Field(index) if err := json.Unmarshal(object[name], field.Addr().Interface()); err != nil { problems = append(problems, fmt.Sprintf("%s: expected %s", name, describe(field.Type()))) } } if len(problems) > 0 { return &PayloadError{Problems: problems} } return nil } // bodyProblem describes why a body is not a JSON object. func bodyProblem(err error) string { var typeErr *json.UnmarshalTypeError switch { case errors.Is(err, io.EOF): return "body: empty; expected a JSON object" case errors.As(err, &typeErr): return "body: expected a JSON object, got " + typeErr.Value } return "body: not valid JSON: " + err.Error() } // jsonFields maps the json name of each exported field of the struct type t // to its index. func jsonFields(t reflect.Type) map[string]int { fields := make(map[string]int, t.NumField()) for i := range t.NumField() { f := t.Field(i) name, _, _ := strings.Cut(f.Tag.Get("json"), ",") if !f.IsExported() || name == "-" { continue } if name == "" { name = f.Name } fields[name] = i } return fields } // fieldName shows a field name from a payload in a problem: as written when // it is a plain name, quoted otherwise, and cut when it is long. func fieldName(name string) string { plain := name != "" && strings.Trim(name, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-") == "" if r := []rune(name); len(r) > maxNameInProblem { name = string(r[:maxNameInProblem]) + "..." } if plain { return name } return strconv.Quote(name) } // describe names the JSON a field of type t takes. func describe(t reflect.Type) string { switch t.Kind() { case reflect.Pointer: return describe(t.Elem()) case reflect.String: return "a string" case reflect.Bool: return "true or false" case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return "a whole number" case reflect.Slice: switch t.Elem().Kind() { case reflect.String: return "an array of strings" case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return "an array of whole numbers" } return "an array" } return t.String() }