SoFunction
Updated on 2025-03-02

Summary of four different parameter configuration methods in Golang

Preface

In the actual development process, we will inevitably use services such as MySQL and Redis. In order to realize the configuration of the system, we will place some configuration information in some files separately and read the configuration file directly where we use it. There are many common file configuration methods, such as json, tomal, yml or text formats. Here are several ways to demonstrate.

Demo code

JSON configuration

First, we create a JSON file to configure the parameter format we need. Example:

{
"host": "127.0.0.1",
"user": "root",
"password": "123456",
"port": "3306",
"db": "demo"

If we want to read the file, we need to use the built-in Golang​json​​Bake. Specific reading process:​Read the content of the json file -> Deserialization using the json package -> Use variables to store the deserialized data​​。

ang
// Use struct to define json format and storage.type DbJson struct {
Host string `json:"host"`
User string `json:"user"`
Password string `json:"password"`
Port string `json:"port"`
Db string `json:"db"`
}
// Analysisfunc GetJsonConfig() {
// 1. Read the content of the json filefile, err := ("./config/")
if err != nil {
("err1", err)
return
}
db := new(DbJson)
// 2. Deserialize the content of the read json file; you will get a slice of []byte typeerr = (file, db)
if err != nil {
("err2", err)
return
}
// 2.1 Deserialize the content of the read json file and copy it to map[string][]byte (the effect is the same as in 2)allConfig := make(map[string], 0)
err = (file, &allConfig)
if err != nil {
("err3", err)
return
}
// 3. Loop map contentfor k, v := range allConfig {
(k, string(v)) // The value is of type []byte, convert it to string}

Final input result:

ang
host "127.0.0.1"
user "root"
password "123456"
port "3306"
db "demo

In fact, both 2 and 2.1 are different implementation methods.

yml configuration

The yml format is also our common file configuration format. In Golang, we mainly use the​/yaml.v2​​Bake. Similarly, we need​Read configuration file->Parse file contents​​. Let's create a​​File, write to the following example configuration:

yml
host: 127.0.0.1
user: root
password: 123456
port: 3306
db: dem

It should be noted that there is a space between the yml configuration item: and the value.

ang
// Define a struct to define the formattype DbYml struct {
Host string `yaml:"host"`
User string `yaml:"user"`
Password string `yaml:"password"`
Port string `yaml:"port"`
Db string `yaml:"db"`
}
func GetYmlConfig() {
// 1. Read the configuration file content and return the content of []bytefile, err := ("./config/")
if err != nil {
return
}
db := new(DbYml)
// 2. Deserialization using yaml packageerr = (file, db)
if err != nil {
return
}
(, , , , )

Final input result:

ang
127.0.0.1 root 123456 3306 dem

Text format

Reading the content in the file format is to read by line and then parse the content of each line. Because the formats in our text are generally sequenced​​key=value​​ format, so we just read the content of the line change and then follow​=​​Just split.

First, we create a file content of .txt, with the rough content as follows:

host=127.0.0.1
user=root
password=123456
port=3306
db=dem

Read the configuration code specifically:

ang
func GetKeyValue() {
allConfig := make(map[string]string)
// 1. Read the file and get the file handleopen, err := ("./config/")
if err != nil {
("err1", err)
return
}
// 2. Read the file contentcontent := (open)
for {
// 3. Read file contents by lineline, _, err := ()
if err != nil {
if err ==  { // Go to the end and read it out of the loopbreak
}
return
}
// 4. Process the file contents read in each lines := (string(line)) // Remove left and right spacesindex := (s, "=") // Because the configuration is =, find the index position of =if index < 0 {
continue
}
key := (s[:index]) // Intercept = The value on the left is keyif len(key) == 0 {
continue
}
value := (s[index+1:]) // Intercept = the value on the rightif len(value) == 0 {
continue
}
allConfig[key] = value // Add to map, key is map key, value is map value}
for k, v := range allConfig {
(k, string(v))
}
defer () // Close the file

The output content is roughly as follows:

ang
host 127.0.0.1
user root
password 123456
port 3306
db dem

tomal

Using toml format configuration files, the toml package is mainly used to parse them. Similarly, first we load the file and pass the file path into the toml package.

First we create a toml file, which defines the following content:

ang
[database]
host="127.0.0.1"
user="root"
password="123456"
port=[3306, 3307]
db="demo

Here is the specific parsing code:

ang
import (
"/BurntSushi/toml"
"path/filepath"
)
type DbToml struct {
Db Database `toml:"database"`
}
type Database struct {
Host string
User string
Password string
Port []int32
Db string
}
func GetToml() {
// 1. Define structure variables to receive parsed datavar config DbToml
// 2. Get the absolute path of the filefileName, err := ("./config/")
if err != nil {
("err1", err)
return
}
// 3. Pass in file path according to the rules of toml package_, err1 := (fileName, &config)
if err1 != nil {
("err2", err1)
return
}
(, , , [0], )

The output result is as follows:

ang
127.0.0.1 root 123456 3306 dem

This is the end of this article about summarizing the four different parameter configuration methods of Golang. For more related Golang parameter configuration content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!