php editor Baicao will introduce to you today a very practical technology - yaml parsing and marshal in golang, and how to process URLs. With golang being widely used in back-end development, understanding and mastering these technologies will greatly improve our development efficiency. This article will briefly introduce the basic concepts and usage of yaml, and demonstrate through examples how to use golang to parse and marshal yaml; at the same time, we will also discuss how to process urls, including parsing url parameters, building urls, etc. I hope that through studying this article, I can help you better apply these technologies in actual projects.
I'm trying to use a config file that has a url field and I want to marshal and unmarshal this type. The documentation states that I can perform a custom marshalling function.
In this golang playground, you can see that the custom unmarshal function works fine, but the custom marshal function does not:
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
do not know why Thanks
The problem is that you wrote the marshalyaml
method for the pointer receiver, so you can call this method on the pointer type while you are The configuration
structurally defines the a
attribute of the uri
as a non-pointer (based on the playground link you pasted).
Therefore, you must change the uri
attribute type to *yamlurl
(instead of yamlurl
):
type a struct { uri *yamlurl `yaml:"url"` }
Or define 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 }
The above is the detailed content of golang yaml marshal url. For more information, please follow other related articles on the PHP Chinese website!