package common import ( "encoding/json" "fmt" "time" ) // PostgreSQL stores microseconds, so keeping the same boundary in Go // prevents a create response from showing more precision // than a later read can reproduce. const storageTimePrecision = time.Microsecond type RFCFormTime time.Time func (t RFCFormTime) MarshalJSON() ([]byte, error) { // RFC 3339 permits an optional fractional second. utc := time.Time(t).UTC().Truncate(storageTimePrecision) layout := "2006-01-02T15:04:05Z" if utc.Nanosecond() != 0 { layout = "2006-01-02T15:04:05.000000Z" } return json.Marshal(utc.Format(layout)) } // UnmarshalJSON accepts the same RFC 3339 strings MarshalJSON emits. The // broker round-trips Job values through JSON, and a named time.Time type does // not inherit encoding/json's time.Time special case on decode. func (t *RFCFormTime) UnmarshalJSON(data []byte) error { if string(data) == "null" { return nil } var raw string if err := json.Unmarshal(data, &raw); err != nil { return err } parsed, err := time.Parse(time.RFC3339Nano, raw) if err != nil { return fmt.Errorf("parse RFC form time: %w", err) } *t = RFCFormTime(parsed) return nil } func NowUTC() RFCFormTime { return RFCFormTime(time.Now().UTC().Truncate(storageTimePrecision)) }