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