ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
## 操作TOML,YAML和JSON配置文件 使用配置文件的好处有很多,例如跨语言共享配置、部署修改方便等。Go对JSON实现了开箱即用的支持。本章主要关注以配置结构体tag标签的形式映射至Go结构。 ### 实践 1. 我们需要安装以下第三方库: ``` go get github.com/BurntSushi/toml go get github.com/go-yaml/yaml ``` 2. 建立toml.go: ``` package confformat import ( "bytes" "github.com/BurntSushi/toml" ) // TOMLData是我们使用TOML结构标记的通用数据结构 type TOMLData struct { Name string `toml:"name"` Age int `toml:"age"` } // ToTOML 将TOMLData结构转储为TOML格式bytes.Buffer func (t *TOMLData) ToTOML() (*bytes.Buffer, error) { b := &bytes.Buffer{} encoder := toml.NewEncoder(b) if err := encoder.Encode(t); err != nil { return nil, err } return b, nil } // Decode 将数据解码为TOMLData func (t *TOMLData) Decode(data []byte) (toml.MetaData, error) { return toml.Decode(string(data), t) } ``` 3. 建立yaml.go: ``` package confformat import ( "bytes" "github.com/go-yaml/yaml" ) // YAMLData 是我们使用YAML结构标记的通用数据结构 type YAMLData struct { Name string `yaml:"name"` Age int `yaml:"age"` } // ToYAML 将YAMLData结构转储为YAML格式bytes.Buffer func (t *YAMLData) ToYAML() (*bytes.Buffer, error) { d, err := yaml.Marshal(t) if err != nil { return nil, err } b := bytes.NewBuffer(d) return b, nil } // Decode 将数据解码为 YAMLData func (t *YAMLData) Decode(data []byte) error { return yaml.Unmarshal(data, t) } ``` 4. 建立json.go: ``` package confformat import ( "bytes" "encoding/json" "fmt" ) // JSONData 是我们使用JSON结构标记的通用数据结构 type JSONData struct { Name string `json:"name"` Age int `json:"age"` } // ToJSON 将JSONData结构转储为JSON格式bytes.Buffer func (t *JSONData) ToJSON() (*bytes.Buffer, error) { d, err := json.Marshal(t) if err != nil { return nil, err } b := bytes.NewBuffer(d) return b, nil } // Decode 将数据解码为JSONData func (t *JSONData) Decode(data []byte) error { return json.Unmarshal(data, t) } // OtherJSONExamples 显示对json解析至其他类型的操作 func OtherJSONExamples() error { res := make(map[string]string) err := json.Unmarshal([]byte(`{"key": "value"}`), &res) if err != nil { return err } fmt.Println("We can unmarshal into a map instead of a struct:", res) b := bytes.NewReader([]byte(`{"key2": "value2"}`)) decoder := json.NewDecoder(b) if err := decoder.Decode(&res); err != nil { return err } fmt.Println("we can also use decoders/encoders to work with streams:", res) return nil } ``` 5. 建立marshal.go: ``` package confformat import "fmt" // MarshalAll 建立了不同结构类型的数据并将它们转换至对应的格式 func MarshalAll() error { t := TOMLData{ Name: "Name1", Age: 20, } j := JSONData{ Name: "Name2", Age: 30, } y := YAMLData{ Name: "Name3", Age: 40, } tomlRes, err := t.ToTOML() if err != nil { return err } fmt.Println("TOML Marshal =", tomlRes.String()) jsonRes, err := j.ToJSON() if err != nil { return err } fmt.Println("JSON Marshal=", jsonRes.String()) yamlRes, err := y.ToYAML() if err != nil { return err } fmt.Println("YAML Marshal =", yamlRes.String()) return nil } ``` 6. 建立 unmarshal.go: ``` package confformat import "fmt" const ( exampleTOML = `name="Example1" age=99 ` exampleJSON = `{"name":"Example2","age":98}` exampleYAML = `name: Example3 age: 97 ` ) // UnmarshalAll 将不同格式的数据转换至对应结构 func UnmarshalAll() error { t := TOMLData{} j := JSONData{} y := YAMLData{} if _, err := t.Decode([]byte(exampleTOML)); err != nil { return err } fmt.Println("TOML Unmarshal =", t) if err := j.Decode([]byte(exampleJSON)); err != nil { return err } fmt.Println("JSON Unmarshal =", j) if err := y.Decode([]byte(exampleYAML)); err != nil { return err } fmt.Println("Yaml Unmarshal =", y) return nil } ``` 7. 建立main.go: ``` package main import "github.com/agtorre/go-cookbook/chapter2/confformat" func main() { if err := confformat.MarshalAll(); err != nil { panic(err) } if err := confformat.UnmarshalAll(); err != nil { panic(err) } if err := confformat.OtherJSONExamples(); err != nil { panic(err) } } ``` 8. 这会输出: ``` TOML Marshal = name = "Name1" age = 20 JSON Marshal= {"name":"Name2","age":30} YAML Marshal = name: Name3 age: 40 TOML Unmarshal = {Example1 99} JSON Unmarshal = {Example2 98} Yaml Unmarshal = {Example3 97} We can unmarshal into a map instead of a struct: map[key:value] we can also use decoders/encoders to work with streams: map[key:value key2:value2] ``` ### 说明 本节给出了使用TOML,YAML和JSON解析器将原始数据写入go结构并从中读取数据并使用相应格式的示例。 与第1章 I/O和文件系统中的示例一样,我们看到在[]byte,string,bytes.Buffer和其他 I/O 接口之间快速切换是多么常见。 encoding/json包对JSON编码提供了全面的支持。我们抽象出这些函数,可以看到快速转换为对应的结构非常简单。 本节还涉及了struct标签及其用法。前一章也使用了这些,并且这是Go中的一种常见方式,用于向包和库提供有关如何处理结构中所包含数据的提示。 此外,Go对xml也支持开箱即用。而配置文件格式还有ini、cfg、properties、plist、config等,大家可以自行查询相应的第三方库。 * * * * 学识浅薄,错误在所难免。欢迎在群中就本书提出修改意见,以飨后来者,长风拜谢。 Golang中国(211938256) beego实战(258969317) Go实践(386056972)