forked from mtusi2026/mtusi2026lab2
Перенесена ЛР1
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"mtusi2026lab2/internal/store"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
store *store.MemoryStore
|
||||
}
|
||||
|
||||
func NewHandler(st *store.MemoryStore) *Handler {
|
||||
return &Handler{store: st}
|
||||
}
|
||||
|
||||
// декодирует тело запроса:
|
||||
// Запрещает неизвестные/лишние поля (DisallowUnknownFields) -> 400
|
||||
// Ловит синтаксические ошибки JSON -> 400
|
||||
// Проверяет, что после валидного JSON нет мусора
|
||||
func decodeJSON(r *http.Request, dst any) error {
|
||||
if r.Body == nil {
|
||||
return errors.New("request body is empty")
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
dec := json.NewDecoder(r.Body)
|
||||
dec.DisallowUnknownFields()
|
||||
|
||||
if err := dec.Decode(dst); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// два JSON подряд или мусор в конце — ошибка
|
||||
var extra json.RawMessage
|
||||
if err := dec.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||
return errors.New("extra data after JSON")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user