github.com/anthropics/anthropic-sdk-go@v1.70.1/internal/apijson/subfield.go (about) 1 package apijson 2 3 import ( 4 "github.com/anthropics/anthropic-sdk-go/packages/respjson" 5 "reflect" 6 ) 7 8 func getSubField(root reflect.Value, index []int, name string) reflect.Value { 9 strct := root.FieldByIndex(index[:len(index)-1]) 10 if !strct.IsValid() { 11 panic("couldn't find encapsulating struct for field " + name) 12 } 13 meta := strct.FieldByName("JSON") 14 if !meta.IsValid() { 15 return reflect.Value{} 16 } 17 field := meta.FieldByName(name) 18 if !field.IsValid() { 19 return reflect.Value{} 20 } 21 return field 22 } 23 24 func setMetadataSubField(root reflect.Value, index []int, name string, meta Field) { 25 target := getSubField(root, index, name) 26 if !target.IsValid() { 27 return 28 } 29 30 if target.Type() == reflect.TypeOf(meta) { 31 target.Set(reflect.ValueOf(meta)) 32 } else if respMeta := meta.toRespField(); target.Type() == reflect.TypeOf(respMeta) { 33 target.Set(reflect.ValueOf(respMeta)) 34 } 35 } 36 37 func setMetadataExtraFields(root reflect.Value, index []int, name string, metaExtras map[string]Field) { 38 target := getSubField(root, index, name) 39 if !target.IsValid() { 40 return 41 } 42 43 if target.Type() == reflect.TypeOf(metaExtras) { 44 target.Set(reflect.ValueOf(metaExtras)) 45 return 46 } 47 48 newMap := make(map[string]respjson.Field, len(metaExtras)) 49 if target.Type() == reflect.TypeOf(newMap) { 50 for k, v := range metaExtras { 51 newMap[k] = v.toRespField() 52 } 53 target.Set(reflect.ValueOf(newMap)) 54 } 55 } 56 57 func (f Field) toRespField() respjson.Field { 58 if f.IsMissing() { 59 return respjson.Field{} 60 } else if f.IsNull() { 61 return respjson.NewField("null") 62 } else if f.IsInvalid() { 63 return respjson.NewInvalidField(f.raw) 64 } else { 65 return respjson.NewField(f.raw) 66 } 67 }