Currently, we usually put the configuration in a separate configuration file, which can be read and modified easily. In the Golang project, there are two types of files that can read the configuration

  • Required knowledge (relative path “./”,”.. The difference between /” and /”)

Blog.csdn.net/qq_34769573…

  • Project directory
Project name | - config | | - app. Ini | - PKG | | - setting | | - setting. Go | - main. GoCopy the code

1. The ini file

1. Obtain third-party packages

import  "github.com/go-ini/ini"
Copy the code

2. Config /app.ini configuration file (example)

RUN_MOD= debug

[server]
HTTP_PORT = 8081
READ_TIMEOUT = 60
WRITE_TIMEOUT = 60
Copy the code

3. PKG/setting. / setting. Go read the Settings

var	Cfg *ini.File

type Server struct{
    HttpPort int
	ReadTimeout  time.Duration
	WriteTimeout time.Duration
}


func InitSetting(a){
    var err error
    Cfg,err=ini.Load("conf")
    iferr ! =nil{
        log.Fatal("Fail to Load 'conf/app. Ini" :",err)
    }
    
    // Read directly
    RunMode := Cfg.Section("").Key("RUN_MODE").MustString("debug")
    
    // Read the internal configuration
    server, err := Cfg.GetSection("server")
	iferr ! =nil {
		log.Fatal("Fail to load section 'server': ", err)
	}
	HttpPort = server.Key("HTTP_PORT").MustUint(8080)
	ReadTimeout = time.Duration(server.Key("READ_TIMEOUT").MustUint(60)) * time.Second
	WriteTimeout = time.Duration(server.Key("WRITE_TIMEOUT").MustUint(60)) * time.Second
}
Copy the code

4. main.go

package main

func main {
	// Initialize the configuration
	setting.InitSetting()
}
Copy the code

2. Yaml files (personal recommendation)

1. Obtain third-party packages

import	"gopkg.in/yaml.v2"
Copy the code

1. Conf /app.yml configuration file

redis:
  host: 127.0. 01.:6379
  passwrod:
  timeout: 200# max_active:30Max_idle:30
Copy the code

PKG /setting/setting.go Reads the configuration

type Set struct {
	Redis   Redis
	Postgre Postgre
	Gin     Gin
}

type Redis struct {
	Host      string `yaml:"host"`
	Password  string `yaml:"password"`
	Timeout   int    `yaml:"timeout"`
	MaxActive int    `yaml:"max_active"`
	MaxIdle   int    `yaml:"max_idle"`
	Db        int
}

var Setting = Set{}

func InitSetting(a) {
   file, err := ioutil.ReadFile("./conf/app.yml")
   iferr ! =nil {
      log.Fatal("fail to read file:", err)
   }

   err = yaml.Unmarshal(file, &Setting)
   iferr ! =nil {
      log.Fatal("fail to yaml unmarshal:", err)
   }

}
Copy the code

3. Refer to official documents

1.ini

github.com/go-ini/ini

2.yml

Github.com/go-yaml/yam…