Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Setting default for non-string type with string schema panics #680

Open
costela opened this issue Dec 13, 2024 · 0 comments
Open

Setting default for non-string type with string schema panics #680

costela opened this issue Dec 13, 2024 · 0 comments
Labels
bug Something isn't working

Comments

@costela
Copy link
Contributor

costela commented Dec 13, 2024

This picks up from this discussion: #228 (comment)

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.

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?

@danielgtaylor danielgtaylor added the bug Something isn't working label Dec 18, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants