golang yaml marshal url 的中文翻译是:golang yaml编组url。

huangapple go评论88阅读模式
英文:

golang yaml marshal url

问题

我正在尝试处理具有URL字段的配置文件,并且我想要编组和解组这种类型。文档指出我可以使用自定义编组函数

在这个 Golang Playground 中,你可以看到自定义的解组函数工作正常,但自定义的编组函数却不起作用:

type YAMLURL struct {
	*url.URL
}

func (j *YAMLURL) UnmarshalYAML(unmarshal func(interface{}) error) error {
	fmt.Println("自定义解组函数")
	var s string
	err := unmarshal(&s)
	if err != nil {
		return err
	}
	url, err := url.Parse(s)
	j.URL = url
	return err
}

func (j *YAMLURL) MarshalYAML() (interface{}, error) {
	fmt.Println("自定义编组函数")
	return j.String(), nil
}

https://go.dev/play/p/24JbJEhi1Q8

我不知道为什么会出现这种情况。谢谢。

英文:

I'm trying to work with configuration files which have url fields and I would like to marshal and unmarshal this type.
The documentation point that I can do a custom marshal function.

In this golang playground you can see that the custom unmarshal function works fine but not the custom marshal function:

type YAMLURL struct {
	*url.URL
}

func (j *YAMLURL) UnmarshalYAML(unmarshal func(interface{}) error) error {
	fmt.Println("custom unmarshal function")
	var s string
	err := unmarshal(&s)
	if err != nil {
		return err
	}
	url, err := url.Parse(s)
	j.URL = url
	return err
}

func (j *YAMLURL) MarshalYAML() (interface{}, error) {
	fmt.Println("custome marshal")
	return j.String(), nil
}

https://go.dev/play/p/24JbJEhi1Q8

I don't know why
Thanks

答案1

得分: 1

问题在于你为指针接收器编写了MarshalYAML方法,因此你可以在指针类型上调用此方法,同时你在Configuration结构体的URI属性上定义了一个非指针(根据你粘贴的playground链接)。

所以你要么将URI属性类型更改为*YAMLURL(而不是YAMLURL):

type A struct {
    URI *YAMLURL `yaml:"url"`
}

要么将MarshalYAML定义为非指针接收器(也称为值接收器),像这样:

func (j YAMLURL) MarshalYAML() (interface{}, error) {
    fmt.Println("custom marshal")
    return j.String(), nil
}
英文:

The problem is that you wrote the MarshalYAML method for a pointer receiver, so you can call this method on a pointer type, meanwhile you defined the URI attribute of your A on Configuration struct, as a non pointer ( based on the playground link you pasted ).

So you have to either change the URI attribute type to *YAMLURL ( instead of YAMLURL ):

type A struct {
	URI *YAMLURL `yaml:"url"`
}

or define the MarshalYAML as a non-pointer receiver ( aka. Value receiver ), like this:

func (j YAMLURL) MarshalYAML() (interface{}, error) {
    fmt.Println("custome marshal")
    return j.String(), nil
}

huangapple
  • 本文由 发表于 2023年3月4日 00:46:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75629763.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定