Files

54 lines
1.7 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package handler
import (
"bytes"
"encoding/json"
"time"
)
// Timestamp подставляется кодогенератором вместо time.Time (codegen.yaml,
// type-mapping): RFC 3339 UTC с ровно шестью цифрами дробной части.
// time.Time срезает хвостовые нули, а fromisoformat в Python 3.9–3.10
// (на нём публичные тесты) понимает дробную часть только из 3 или 6 цифр.
type Timestamp time.Time
const timestampLayout = "2006-01-02T15:04:05.000000Z"
func (t Timestamp) MarshalJSON() ([]byte, error) {
return []byte(`"` + time.Time(t).UTC().Format(timestampLayout) + `"`), nil
}
func (t *Timestamp) UnmarshalJSON(data []byte) error {
var parsed time.Time
if err := json.Unmarshal(data, &parsed); err != nil {
return err
}
*t = Timestamp(parsed)
return nil
}
// Тела запросов с лишними полями — 400 по контракту, а сгенерированный
// декодер их молча игнорирует. Строгий разбор подключается методами на
// сгенерированных типах.
func (c *CreateUser) UnmarshalJSON(data []byte) error {
type plain CreateUser
return decodeStrict(data, (*plain)(c))
}
func (c *CreateChat) UnmarshalJSON(data []byte) error {
type plain CreateChat
return decodeStrict(data, (*plain)(c))
}
func (c *CreateMessage) UnmarshalJSON(data []byte) error {
type plain CreateMessage
return decodeStrict(data, (*plain)(c))
}
func decodeStrict(data []byte, dst any) error {
dec := json.NewDecoder(bytes.NewReader(data))
dec.DisallowUnknownFields()
return dec.Decode(dst)
}