danielgtaylor / danielgtaylor/huma

Unexported Fields in Schemas are Not Considered for Schema Generation

Open
#444 5 comments 0 reactions 0 assignees View on GitHub
question
Dominant language
Go
Stars
4.4k
Forks
285
Avg merge
40m
Merged PRs (30d)
1

Description

Currently in the process of building some of the more complex schemas for an OpenAPI-based API and running into some new issues. I have an example that looks something like this:

In models.go
```go
type commonElems struct {
Inner string `json:"inner"`
}

type V1 struct {
A int `json:"a"`
commonElems
}

type V2 struct {
B int `json:"b"`
commonElems
}
```

In main.go:
```go
func main() {
x := controller.V1{}
// It is still possible to access the contents of commonElems
x.Inner = "Hello"

registry := huma.NewMapRegistry("#/prefix", huma.DefaultSchemaNamer)
t := reflect.TypeOf(controller.V1{})
schema := huma.SchemaFromType(registry, t)
fmt.Printf("Schema: %v\n", schema)
}
```

The output only contains the outer field
```
Schema: &{object false [] false map[a:0x140001f6008] [] false [a] false false false map[] map[] [] [] [] map[a:true] [a] expected value to be one of "" map[a:expected required property a to be present] map[]}
```

Changing `commonElems` to `CommonElems` so the embedded struct is exported, the output contains both expected fields:
```
Schema: &{object false [] false map[a:0x14000254008 inner:0x14000254308] [] false [a inner] false false false map[] map[] [] [] [] map[a:true inner:true] [a inner] expected value to be one of "" map[a:expected required property a to be present inner:expected required property inner to be present] map[]}
```

Unfortunately, unlike the example, the structs V1 and V2 are located in another library that I don't have easy control over. But furthermore, I think the second output should be the default, since in Go we can still access exported fields inside of unexported embedded structs (as seen in the code example) and JSON marshalling/unmarshalling works the same. What are others thoughts?

Contributor guide

No contributing guide indexed for this repository

Research direction

Reproduce the issue with the models.go and main.go examples, starting at huma.SchemaFromType and the registry setup. Compare schema generation for the unexported embedded commonElems and exported CommonElems; done means the generated V1 schema includes the exported inner field in the unexported embedded struct, with regression coverage for the behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
go
Domain
api, backend-api-design
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.