SoFunction
Updated on 2025-03-05

Summary of how Go reads configuration files

Common configuration file formats

File (.xml): This is an extensible markup language that allows users to define their own markup. XML files are a common configuration file because they are easy to read and write, while supporting nesting, making them ideal for storing complex data.

File (.json): JSON (JavaScript Object Notation) is a lightweight data exchange format that is easy to read and write. It is the main way to create objects in JavaScript, so it is particularly common in web applications.

File (.ini): INI files are a configuration file format that Windows applications often use. The INI file consists of sections, under which is a set of key-value pairs.

File (.yaml/.yml): YAML is the abbreviation (recursive abbreviation) of "YAML Ain't Markup Language", a human-friendly readable data serialization standard used for data exchange in all programming languages.

5. .env file: This is a simple key-value pair format file used to store environment variables. The advantage of this format is that it can be easily integrated with environment variables, which is key in many programming environments.

6. .properties file: This is a file used in Java language to store configuration information, and data is stored in the form of key-value pairs.

Next, I will demonstrate how to read common formats in the code

XML format

To read XML files in Go, we can use Go's "encoding/xml" package.

Create a new cd_catalog.xml file

<?xml version="1.0" encoding="UTF-8"?>
<CATALOG>
    <CD>
        <TITLE>Empire Burlesque</TITLE>
        <ARTIST>Bob Dylan</ARTIST>
        <YEAR>1985</YEAR>
    </CD>
    <CD>
        <TITLE>Hide your heart</TITLE>
        <ARTIST>Bonnie Tyler</ARTIST>
        <YEAR>1988</YEAR>
    </CD>
    <CD>
        <TITLE>Greatest Hits</TITLE>
        <ARTIST>Dolly Parton</ARTIST>
        <YEAR>2000</YEAR>
    </CD>
</CATALOG>

Go's full code

package main

import (
    "encoding/xml"
    "os"
    "fmt"
    "log"
)

type CD struct {
    Title  string `xml:"TITLE"`
    Artist string `xml:"ARTIST"`
    Year   string `xml:"YEAR"`
}

type CDs struct {
    CD []CD `xml:"CD"`
}

func main() {
    file, err := ("cd_catalog.xml") // Replace with your xml file
    if err != nil {
        (err)
    }

    decoder := (file)

    var cds CDs
    err = (&cds)
    if err != nil {
      (err)
    }

    for i := range  {
        ([i].Title, [i].Artist, [i].Year)
    }
}

JSON format

The json format is similar to the xml content, but the encoding/json referenced

type Config struct {
    Server string `json:"server"`
    Port   int    `json:"port"`
}

func main() {
    file, err := ("")
    if err != nil {
        ("Failed to open file: %s", err)
    }

    config := Config{}
    decoder := (file)
    if err := (&amp;config); err != nil {
        ("Failed to decode JSON: %s", err)
    }

    //User configuration information    ()
    ()
}

INI format

1. Download the specified extension package

go get /go-ini/ini

2. Create a file

[server]
host = localhost
port = 8080

3. Go code

package main

import (
  "log"

  ini "/go-ini/ini"
)

type Config struct {
  Server struct {
    Host string
    Port int
  } `ini:"server"`
}

func main() {
  cfg := new(Config)
  err := (cfg, "path/to/")
  if err != nil {
    (err)
  }

  ("Server Host:", )
  ("Server Port:", )
}

YAML format

yaml file

server: localhost
port: 8080

Install the yaml.v2 library by running go get /yaml.v2

package main

import (
    "/yaml.v2"
    "io/ioutil"
    "log"
)

type Config struct {
    Server string `yaml:"server"`
    Port   int    `yaml:"port"`
}

func main() {
    data, err := ("/path/to/your/yaml/")
    if err != nil {
        ("error: %v", err)
    }

    config := Config{}
    err = (data, &amp;config)
    if err != nil {
        ("error: %v", err)
    }

    //User configuration information    ()
    ()
}

Note: Please replace /path/to/your/yaml/ in your code with the actual path to your YAML file.

Summarize

XML file (.xml):

  • Advantages: Unified format, suitable for complex hierarchical relationship data, and supports verification syntax.
  • Disadvantages: Reading and writing is relatively cumbersome, and the performance is poor when the files are slightly larger.

JSON file (.json):

  • Advantages: Lightweight, flexible format, easy to read and write, and good performance.
  • Disadvantages: Not suitable for super-large and complex hierarchical relationship data.

INI file (.ini):

  • Advantages: Simple, easy to read and write, suitable for storing simple configuration data.
  • Disadvantages: Unable to effectively handle complex data structures.

YAML file (.yaml/.yml):

  • Advantages: It is highly readable and can represent complex data structures, suitable for use in configuration files.
  • Disadvantages: rigorous grammar, sensitive indentation, easy to operate incorrectly.

.env file:

  • Advantages: Lightweight, simple, mainly used to store environment variables.
  • Disadvantages: The format is concise, the purpose is single, and it cannot represent complex data types.

.properties file:

  • Advantages: It is often used in configuration in Java environment, with a simple format.
  • Disadvantages: The function is relatively simple and cannot handle complex data structures.

The above is the detailed summary of the method of Go to read configuration files. For more information about Go to read configuration files, please pay attention to my other related articles!