forked from mtusi2026/mtusi2026lab3
внес правки
This commit is contained in:
@@ -1,11 +1,14 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type errorCode string
|
||||
@@ -44,13 +47,41 @@ func writeError(w http.ResponseWriter, status int, requestID string, code errorC
|
||||
})
|
||||
}
|
||||
|
||||
func jsonFieldNames(dst any) map[string]bool {
|
||||
names := map[string]bool{}
|
||||
t := reflect.TypeOf(dst)
|
||||
for t.Kind() == reflect.Ptr {
|
||||
t = t.Elem()
|
||||
}
|
||||
for i := 0; i < t.NumField(); i++ {
|
||||
tag := strings.Split(t.Field(i).Tag.Get("json"), ",")[0]
|
||||
if tag != "" && tag != "-" {
|
||||
names[tag] = true
|
||||
}
|
||||
}
|
||||
return names
|
||||
}
|
||||
func decodeJSONStrict(r *http.Request, dst any) error {
|
||||
dec := json.NewDecoder(r.Body)
|
||||
raw, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(bytes.TrimSpace(raw)) == 0 {
|
||||
return fmt.Errorf("empty body")
|
||||
}
|
||||
var probe map[string]json.RawMessage
|
||||
if err := json.Unmarshal(raw, &probe); err != nil {
|
||||
return err
|
||||
}
|
||||
allowed := jsonFieldNames(dst)
|
||||
for k := range probe {
|
||||
if !allowed[k] {
|
||||
return fmt.Errorf("unknown field %q", k)
|
||||
}
|
||||
}
|
||||
dec := json.NewDecoder(bytes.NewReader(raw))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(dst); err != nil {
|
||||
if err == io.EOF {
|
||||
return fmt.Errorf("empty body")
|
||||
}
|
||||
return err
|
||||
}
|
||||
if dec.More() {
|
||||
|
||||
Reference in New Issue
Block a user