|
7 | 7 | "encoding/json" |
8 | 8 | "errors" |
9 | 9 | "fmt" |
| 10 | + |
| 11 | + "github.com/go-openapi/swag/jsonname" |
10 | 12 | ) |
11 | 13 |
|
12 | 14 | var ErrExampleStruct = errors.New("example error") |
@@ -185,3 +187,49 @@ func ExamplePointer_Set_appendTopLevelSlice() { |
185 | 187 | // original: [1 2] |
186 | 188 | // returned: [1 2 3] |
187 | 189 | } |
| 190 | + |
| 191 | +// ExampleUseGoNameProvider contrasts the two [NameProvider] implementations |
| 192 | +// shipped by [github.com/go-openapi/swag/jsonname]: |
| 193 | +// |
| 194 | +// - the default provider requires a `json` struct tag to expose a field; |
| 195 | +// - the Go-name provider follows encoding/json conventions and accepts |
| 196 | +// exported untagged fields and promoted embedded fields as well. |
| 197 | +func ExampleUseGoNameProvider() { |
| 198 | + type Embedded struct { |
| 199 | + Nested string // untagged: promoted only by the Go-name provider |
| 200 | + } |
| 201 | + type Doc struct { |
| 202 | + Embedded // untagged embedded: promoted only by the Go-name provider |
| 203 | + |
| 204 | + Tagged string `json:"tagged"` |
| 205 | + Untagged string // no tag: visible only to the Go-name provider |
| 206 | + } |
| 207 | + |
| 208 | + doc := Doc{ |
| 209 | + Embedded: Embedded{Nested: "promoted"}, |
| 210 | + Tagged: "hit", |
| 211 | + Untagged: "hidden-by-default", |
| 212 | + } |
| 213 | + |
| 214 | + for _, path := range []string{"/tagged", "/Untagged", "/Nested"} { |
| 215 | + p, err := New(path) |
| 216 | + if err != nil { |
| 217 | + fmt.Println(err) |
| 218 | + |
| 219 | + return |
| 220 | + } |
| 221 | + |
| 222 | + // Default provider: only the tagged field resolves. |
| 223 | + defV, _, defErr := p.Get(doc) |
| 224 | + // Go-name provider: untagged and promoted fields resolve too. |
| 225 | + goV, _, goErr := p.Get(doc, WithNameProvider(jsonname.NewGoNameProvider())) |
| 226 | + |
| 227 | + fmt.Printf("%s -> default=%v (err=%v) | goname=%v (err=%v)\n", |
| 228 | + path, defV, defErr != nil, goV, goErr != nil) |
| 229 | + } |
| 230 | + |
| 231 | + // Output: |
| 232 | + // /tagged -> default=hit (err=false) | goname=hit (err=false) |
| 233 | + // /Untagged -> default=<nil> (err=true) | goname=hidden-by-default (err=false) |
| 234 | + // /Nested -> default=<nil> (err=true) | goname=promoted (err=false) |
| 235 | +} |
0 commit comments