testType fetches the JSON resource at urlStr and compares its keys to the struct fields of typ.
(urlStr string, typ any)
| 76 | // testType fetches the JSON resource at urlStr and compares its keys to the |
| 77 | // struct fields of typ. |
| 78 | func testType(urlStr string, typ any) error { |
| 79 | ctx := context.Background() |
| 80 | slice := reflect.Indirect(reflect.ValueOf(typ)).Kind() == reflect.Slice |
| 81 | |
| 82 | req, err := client.NewRequest(ctx, "GET", urlStr, nil) |
| 83 | if err != nil { |
| 84 | return err |
| 85 | } |
| 86 | |
| 87 | // start with a json.RawMessage so we can decode multiple ways below |
| 88 | raw := new(json.RawMessage) |
| 89 | _, err = client.Do(req, raw) |
| 90 | if err != nil { |
| 91 | return err |
| 92 | } |
| 93 | |
| 94 | // unmarshal directly to a map |
| 95 | var m1 map[string]any |
| 96 | if slice { |
| 97 | var s []map[string]any |
| 98 | err = json.Unmarshal(*raw, &s) |
| 99 | if err != nil { |
| 100 | return err |
| 101 | } |
| 102 | m1 = s[0] |
| 103 | } else { |
| 104 | err = json.Unmarshal(*raw, &m1) |
| 105 | if err != nil { |
| 106 | return err |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | // unmarshal to typ first, then re-marshal and unmarshal to a map |
| 111 | err = json.Unmarshal(*raw, typ) |
| 112 | if err != nil { |
| 113 | return err |
| 114 | } |
| 115 | |
| 116 | var byt []byte |
| 117 | if slice { |
| 118 | // use first item in slice |
| 119 | v := reflect.Indirect(reflect.ValueOf(typ)) |
| 120 | byt, err = json.Marshal(v.Index(0).Interface()) |
| 121 | if err != nil { |
| 122 | return err |
| 123 | } |
| 124 | } else { |
| 125 | byt, err = json.Marshal(typ) |
| 126 | if err != nil { |
| 127 | return err |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | var m2 map[string]any |
| 132 | err = json.Unmarshal(byt, &m2) |
| 133 | if err != nil { |
| 134 | return err |
| 135 | } |
no test coverage detected
searching dependent graphs…