danielgtaylor / danielgtaylor/huma
Setting default for non-string type with string schema panics
- Dominant language
- Go
- Stars
- 4.4k
- Forks
- 285
- Avg merge
- 40m
- Merged PRs (30d)
- 1
Description
This picks up from this discussion: https://github.com/danielgtaylor/huma/issues/228#issuecomment-1946513763
Currently, using a custom type with different schema type and underlying go type panics.
In the example below, the schema type is `string` (via implementing `encoding.TextUnmarshaler`), but the go type is not a string.
```go
package main
import (
"context"
"net/http"
"time"
"github.com/danielgtaylor/huma/v2"
"github.com/danielgtaylor/huma/v2/adapters/humago"
)
type MyDuration struct {
time.Duration
}
func (d *MyDuration) UnmarshalText(data []byte) error {
v, err := time.ParseDuration(string(data))
if err != nil {
return err
}
d.Duration = v
return nil
}
func main() {
router := http.NewServeMux()
api := humago.New(router, huma.DefaultConfig("My API", "1.0.0"))
huma.Register(api, huma.Operation{
OperationID: "demo",
Method: http.MethodGet,
Path: "/demo",
}, func(ctx context.Context, i *struct {
Duration MyDuration `json:"duration" query:"duration" default:"10s"` // default → 💥
}) (*struct{}, error) {
return nil, nil
})
http.ListenAndServe(":8888", router)
}
```
This leads to:
```
panic: unable to convert string to main.MyDuration for field 'Duration': schema is invalid
```
I suspect `convertType` must be extended to also recognize the same special-casing for types that can be converted to strings?
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.