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

Unable to load configs into custom types #4431

Open
wjiec opened this issue Oct 21, 2024 · 2 comments
Open

Unable to load configs into custom types #4431

wjiec opened this issue Oct 21, 2024 · 2 comments

Comments

@wjiec
Copy link
Contributor

wjiec commented Oct 21, 2024

Describe the bug
Unable to load configs with custom types and as well as custom UnmarshalYAML implementations.

To Reproduce

  1. The code is
//
// internal/config/config.go
//
type Config struct {
	rest.RestConf
	Schedule DurationOrCronSpec
}

type DurationOrCronSpec struct {
	dur  time.Duration
	spec string
}

func (d *DurationOrCronSpec) UnmarshalYAML(value *yaml.Node) error {
	if value.Kind != yaml.ScalarNode {
		return fmt.Errorf("pipeline must contain YAML scalar, has %v", value.Kind)
	}

	if err := value.Decode(&d.dur); err != nil {
		return value.Decode(&d.spec)
	}
	return nil
}
//
// etc/greet.yaml
//
Name: ping
Host: 127.0.0.1
Port: 8888
Log:
  Encoding: plain
Schedule: 20m
  1. The error is

    2024/10/21 09:19:39 error: config file etc/greet.yaml, type mismatch for field "Schedule"
    

Expected behavior
Load configuration files correctly

Environments (please complete the following information):

  • OS: Ubuntu 22.04.4 LTS
  • go-zero version: v1.7.3
  • goctl version: goctl version 1.7.3 linux/amd64

More description
I think that's enough.

@kesonan
Copy link
Collaborator

kesonan commented Oct 21, 2024

Obviously, you declared a structure, but the yaml file contains a string. The types do not match.

@wjiec
Copy link
Contributor Author

wjiec commented Oct 22, 2024

@kesonan Thanks for the quick reply, as you can see, in order to convert the string type to the struct type I need, I implemented a unmarshaler to enable custom unmarshal of the string. But from the code it looks like go-zero first deserializes the YAML data into a map[string]any object and then tries to assign from the map object to the corresponding Config structure, which obviously loses support for yaml.Unmarshaler.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants