Home > Backend Development > Golang > golang yaml marshal url

golang yaml marshal url

WBOY
Release: 2024-02-10 13:33:19
forward
566 people have browsed it

golang yaml marshal url

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.

Question content

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
}
Copy after login

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

do not know why Thanks

Workaround

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"`
}
Copy after login

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
}
Copy after login

The above is the detailed content of golang yaml marshal url. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template