forked from mtusi2026/mtusi2026lab3
87 lines
2.4 KiB
Go
87 lines
2.4 KiB
Go
package handler
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"mime"
|
|
"net/http"
|
|
"reflect"
|
|
"strings"
|
|
"unicode/utf8"
|
|
)
|
|
|
|
const maxBodyBytes = 1 << 20
|
|
|
|
func writeJSON(w http.ResponseWriter, status int, v any) {
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
w.WriteHeader(status)
|
|
_ = json.NewEncoder(w).Encode(v)
|
|
}
|
|
|
|
func decodeJSON(w http.ResponseWriter, r *http.Request, dst any) error {
|
|
mt, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
|
if err != nil || mt != "application/json" {
|
|
return &apiError{http.StatusUnsupportedMediaType, "unsupported_media_type", "Content-Type must be application/json"}
|
|
}
|
|
|
|
raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxBodyBytes))
|
|
if err != nil {
|
|
var tooLarge *http.MaxBytesError
|
|
if errors.As(err, &tooLarge) {
|
|
return &apiError{http.StatusRequestEntityTooLarge, "payload_too_large", "request body is too large"}
|
|
}
|
|
return badRequest("failed to read request body")
|
|
}
|
|
if !utf8.Valid(raw) {
|
|
return badRequest("request body must be valid UTF-8")
|
|
}
|
|
if err := checkKeys(raw, dst); err != nil {
|
|
return err
|
|
}
|
|
|
|
dec := json.NewDecoder(bytes.NewReader(raw))
|
|
dec.DisallowUnknownFields()
|
|
if err := dec.Decode(dst); err != nil {
|
|
return badRequest("request body must be a valid JSON object matching the schema")
|
|
}
|
|
if err := dec.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
|
|
return badRequest("request body must contain a single JSON object")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func checkKeys(raw []byte, dst any) error {
|
|
allowed := jsonFields(dst)
|
|
dec := json.NewDecoder(bytes.NewReader(raw))
|
|
if tok, err := dec.Token(); err != nil || tok != json.Delim('{') {
|
|
return badRequest("request body must be a JSON object")
|
|
}
|
|
for dec.More() {
|
|
tok, err := dec.Token()
|
|
if err != nil {
|
|
return badRequest("request body must be a valid JSON object matching the schema")
|
|
}
|
|
key, _ := tok.(string)
|
|
if !allowed[key] {
|
|
return badRequest("request body contains unknown field")
|
|
}
|
|
var value json.RawMessage
|
|
if err := dec.Decode(&value); err != nil {
|
|
return badRequest("request body must be a valid JSON object matching the schema")
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func jsonFields(dst any) map[string]bool {
|
|
t := reflect.TypeOf(dst).Elem()
|
|
fields := make(map[string]bool, t.NumField())
|
|
for i := range t.NumField() {
|
|
name, _, _ := strings.Cut(t.Field(i).Tag.Get("json"), ",")
|
|
fields[name] = true
|
|
}
|
|
return fields
|
|
}
|