Go language read YAML configuration file, convert to struct structure, output in JSON form

Source: Internet
Author: User
Tags readfile


1, example 11.1, Yaml file contents are as follows:
host: localhost:3306
user: root
pwd: 123456
dbname: test
1.2, the code is as follows:
// Convert the yaml file into an object, and then convert it into json format output
package main

import (
    "encoding / json"
    "fmt"
    "gopkg.in/yaml.v2"
    "io / ioutil"
)

// define conf type
// The attributes in the type are all attributes in the configuration file
type conf struct {
    Host string `yaml:" host "`
    User string `yaml:" user "`
    Pwd string `yaml:" pwd "`
    Dbname string `yaml:" dbname "`
}

func main () {
    var c conf
    // Read the yaml configuration file
    conf: = c.getConf ()
    fmt.Println (conf)

    // Convert the object to json format
    data, err: = json.Marshal (conf)

    if err! = nil {
        fmt.Println ("err: \ t", err.Error ())
        return
    }

    // Finally in json format, output
    fmt.Println ("data: \ t", string (data))
}

// Read Yaml configuration file,
// and convert to conf object
func (c * conf) getConf () * conf {
    // should be absolute address
    yamlFile, err: = ioutil.ReadFile ("E: \\ Program \\ go2 \\ goPath \\ src \\ xingej-go \\ xingej-go \\ xingej-go666 \\ lib \\ yaml \\ conf.yaml ")
    if err! = nil {
        fmt.Println (err.Error ())
    }

    err = yaml.Unmarshal (yamlFile, c)

    if err! = nil {
        fmt.Println (err.Error ())
    }

    return c
}


If a package is not available locally, you can use the following command in cmd to download it, such as:
Go get gopkg.in/yaml.v2



= = Basic Format: = = The path of the go get package


2, Example 2, the configuration file, there is a map,slice type, slightly more complex 2.1, configuration file content:
apiVersion: v1
kind: KafkaCluster2
metadata:
  name: kafka-operator
  labels:
    config1:
      address: kafka-operator-labels-01
      id: kafka-operator-labels-02
      name: mysql-example-cluster-master
      nodeName: 172.16.91.21
      role: master
    config2:
       address: kafka-operator-labels-01
       id: kafka-operator-labels-02
       name: mysql-example-cluster-slave
       nodeName: 172.16.91.110
       role: slave
spec:
  replicas: 1
  name: kafka-controller
  image: 172.16.26.4:5000/nginx
  ports: 8088
  conditions:
    - containerPort: 8080
      requests:
        cpu: "0.25"
        memory: "512Mi"
      limits:
        cpu: "0.25"
        memory: "1Gi"
    - containerPort: 9090
      requests:
        cpu: "0.33"
        memory: "333Mi"
      limits:
        cpu: "0.55"
        memory: "5Gi"
2.2, the code is as follows:
package main

import (
    "encoding / json"
    "fmt"
    "gopkg.in/yaml.v2"
    "io / ioutil"
)

type KafkaCluster struct {
    ApiVersion string `yaml:" apiVersion "`
    Kind string `yaml:" kind "`
    Metadata Metadata `yaml:" metadata "`
    Spec Spec `yaml:" spec "`
}

type Metadata struct {
    Name string `yaml:" name "`
    // map type
    Labels map [string] * NodeServer `yaml:" labels "`
}

type NodeServer struct {
    Address string `yaml:" address "`
    Id string `yaml:" id "`
    Name string `yaml:" name "`
    // Note that if there is an uppercase in the attribute, there must be no spaces in the tag
    // such as yaml: The format of "nodeName" is wrong, there is a space in the middle and it is not recognized
    NodeName string `yaml:" nodeName "`
    Role string `yaml:" role "`
}

type Spec struct {
    Replicas int `yaml:" replicas "`
    Name string `yaml:" name "`
    Image string `yaml:" iamge "`
    Ports int `yaml:" ports "`
    // slice type
    Conditions [] Conditions `yaml:" conditions "`
}

type Conditions struct {
    ContainerPort string `yaml:" containerPort "`
    Requests Requests `yaml:" requests "`
    Limits Limits `yaml:" limits "`
}

type Requests struct {
    CPU string `yaml:" cpu "`
    MEMORY string `yaml:" memory "`
}

type Limits struct {
    CPU string `yaml:" cpu "`
    MEMORY string `yaml:" memory "`
}

func main () {
    var c KafkaCluster
    // Read yaml configuration file, convert yaml configuration file, convert struct type
    conf: = c.getConf ()

    // Convert the object to json format
    data, err: = json.Marshal (conf)

    if err! = nil {
        fmt.Println ("err: \ t", err.Error ())
        return
    }

    // Finally in json format, output
    fmt.Println ("data: \ t", string (data))
}

// Read Yaml configuration file,
// and convert to conf object struct structure
func (kafkaCluster * KafkaCluster) getConf () * KafkaCluster {
    // should be absolute address
    yamlFile, err: = ioutil.ReadFile ("E: \\ Program \\ go2 \\ goPath \\ src \\ xingej-go \\ xingej-go \\ xingej-go666 \\ lib \\ yaml \\ sparkConfig.yaml ")
    if err! = nil {
        fmt.Println (err.Error ())
    }

    // err = yaml.Unmarshal (yamlFile, kafkaCluster)
    err = yaml.UnmarshalStrict (yamlFile, kafkaCluster)

    if err! = nil {
        fmt.Println (err.Error ())
    }

    return kafkaCluster
}
2.3. Operation Result:
data:    {"ApiVersion":"v1","Kind":"KafkaCluster2","Metadata":{"Name":"kafka-operator","Labels":{"config1":{"Address":"kafka-operator-labels-01","Id":"kafka-operator-labels-02","Name":"mysql-example-cluster-master","NodeName":"172.16.91.21","Role":"master"},"config2":{"Address":"kafka-operator-labels-01","Id":"kafka-operator-labels-02","Name":"mysql-example-cluster-slave","NodeName":"172.16.91.110","Role":"slave"}}},"Spec":{"Replicas":1,"Name":"kafka-controller","Image":"172.16.26.4:5000/nginx","Ports":8088,"Conditions":[{"ContainerPort":"8080","Requests":{"CPU":"0.25","MEMORY":"512Mi"},"Limits":{"CPU":"0.25","MEMORY":"1Gi"}},{"ContainerPort":"9090","Requests":{"CPU":"0.33","MEMORY":"333Mi"},"Limits":{"CPU":"0.55","MEMORY":"5Gi"}}]}}


= = Note: = =


In the yaml configuration file, if there is an uppercase in the attribute, there must be no spaces when defining the corresponding attribute. You can refer to the description in the NodeServer in the example above.
3 Example 3, read one of the properties in the Yaml configuration file 3.1, the contents of the configuration file:
apiVersion: v1
Kind: KafkaCluster
3.2, the code is as follows:
// Test read yaml file
package main

import (
     "fmt"
     "github.com/kylelemons/go-gypsy/yaml"
)

func main () {
     file, err: = yaml.ReadFile ("E: \\ Program \\ go2 \\ goPath \\ src \\ xingej-go \\ xingej-go \\ xingej-go666 \\ lib \\ yaml \\ nginx")

     if err! = nil {
         panic (err.Error ())
     }

     apiVersion, error: = file.Get ("apiVersion")
     if error! = nil {
         panic (error.Error ())
     }

     fmt.Println ("= apiVersion ===: \ t", apiVersion)

}
3.3. Operation Result:
=apiVersion===:
4. Description
The yaml parsing package used in Example 3 is not the same as the previous two examples.

"gopkg.in/yaml.v2"
"github.com/kylelemons/go-gypsy/yaml"

Example 1, Example 2 is to read the Yaml configuration file as a whole and convert it to other formats

Example 3 is to read a certain attribute in the yaml configuration,

Therefore, the usage scenarios of the two are different. 


Go language read YAML configuration file, convert to struct structure, output in JSON form


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.