fix: json decoder and uuid dubles

This commit is contained in:
TAskMAster339
2026-10-15 22:15:58 +03:00
parent 70e31f6fdc
commit a9557fa221
4 changed files with 199 additions and 7 deletions
+26 -3
View File
@@ -5,6 +5,7 @@ import (
"fmt"
"io"
"net/http"
"reflect"
"strings"
"messenger/src/backend/services"
@@ -18,8 +19,8 @@ type createUserRequest struct {
func decodeJSONBody(r *http.Request, destination any) error {
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(destination); err != nil {
var body json.RawMessage
if err := decoder.Decode(&body); err != nil {
return err
}
var extra any
@@ -29,7 +30,29 @@ func decodeJSONBody(r *http.Request, destination any) error {
}
return fmt.Errorf("more than one JSON value")
}
return nil
var fields map[string]json.RawMessage
if err := json.Unmarshal(body, &fields); err != nil {
return err
}
if fields == nil {
return fmt.Errorf("JSON body must be an object")
}
// encoding/json matches struct fields case-insensitively, even with
// DisallowUnknownFields. Check exact contract names before decoding values.
typeOfRequest := reflect.TypeOf(destination).Elem()
allowed := make(map[string]bool, typeOfRequest.NumField())
for i := 0; i < typeOfRequest.NumField(); i++ {
name := strings.Split(typeOfRequest.Field(i).Tag.Get("json"), ",")[0]
if name != "" && name != "-" {
allowed[name] = true
}
}
for name := range fields {
if !allowed[name] {
return fmt.Errorf("unknown JSON field %q", name)
}
}
return json.Unmarshal(body, destination)
}
func createUserHandler(users *services.UserService) http.HandlerFunc {