github.com/anthropics/anthropic-sdk-go@v1.70.1/internal/encoding/json/time.go (about) 1 // EDIT(begin): custom time marshaler 2 package json 3 4 import ( 5 "github.com/anthropics/anthropic-sdk-go/internal/encoding/json/shims" 6 "reflect" 7 "time" 8 ) 9 10 type TimeMarshaler interface { 11 MarshalJSONWithTimeLayout(string) []byte 12 } 13 14 func TimeLayout(fmt string) string { 15 switch fmt { 16 case "", "date-time": 17 return time.RFC3339 18 case "date": 19 return time.DateOnly 20 default: 21 return fmt 22 } 23 } 24 25 var timeType = shims.TypeFor[time.Time]() 26 27 func newTimeEncoder() encoderFunc { 28 return func(e *encodeState, v reflect.Value, opts encOpts) { 29 t := v.Interface().(time.Time) 30 fmtted := t.Format(TimeLayout(opts.timefmt)) 31 stringEncoder(e, reflect.ValueOf(fmtted), opts) 32 } 33 } 34 35 // Uses continuation passing style, to add the timefmt option to k 36 func continueWithTimeFmt(timefmt string, k encoderFunc) encoderFunc { 37 return func(e *encodeState, v reflect.Value, opts encOpts) { 38 opts.timefmt = timefmt 39 k(e, v, opts) 40 } 41 } 42 43 func timeMarshalEncoder(e *encodeState, v reflect.Value, opts encOpts) bool { 44 tm, ok := v.Interface().(TimeMarshaler) 45 if !ok { 46 return false 47 } 48 49 b := tm.MarshalJSONWithTimeLayout(opts.timefmt) 50 if b != nil { 51 e.Grow(len(b)) 52 out := e.AvailableBuffer() 53 out, _ = appendCompact(out, b, opts) 54 e.Buffer.Write(out) 55 return true 56 } 57 58 return false 59 } 60 61 // EDIT(end)