Golang项目中读取配置文件

Golang
379
0
0
2022-04-24
标签   Golang基础

目前我们一般都是将配置单独放在一个配置文件中,读取该文件,也方便修改,golang项目中有两种文件可以读取配置

项目名
  |-config
  |    |-app.ini
  |-pkg
  |    |-setting
  |        |-setting.go
  |-main.go

1. ini 文件

1.获取第三方包

import  "github.com/go-ini/ini"

2. config/app.ini配置文件(例子)

RUN_MOD= debug

[server]
HTTP_PORT = 8081
READ_TIMEOUT = 60
WRITE_TIMEOUT = 60

3.pkg/setting./setting.go读取设置

var    Cfg *ini.File

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

func InitSetting(){
    var err error
    Cfg,err=ini.Load("conf")
    if err != nil{
        log.Fatal("Fail to Load ‘conf/app.ini’:",err)
    }
    //直接读取
    RunMode := Cfg.Section("").Key("RUN_MODE").MustString("debug")
    //读取内部配置
    server, err := Cfg.GetSection("server")
    if err != 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
}

4. main.go

package main

func main {
    //初始化配置
    setting.InitSetting()
}

2.yaml 文件(个人推荐使用)

1.获取第三方包

import    "gopkg.in/yaml.v2"

1.conf/app.yml配置文件

redis: 
  host: 127.0.0.1:6379 
  passwrod: 
  timeout: 200 
  #  最大活动连接数 
  max_active: 30 
  #  最大闲置连接 
  max_idle: 30

pkg/setting/setting.go读取配置

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() {
   file, err := ioutil.ReadFile("./conf/app.yml")
   if err != nil {
      log.Fatal("fail to read file:", err)
   }

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

4. main.go

package main
func main {
    //初始化配置
    setting.InitSetting()
}

3.官方文档参考

1.ini

github.com/go-ini/ini

2.yml

github.com/go-yaml/yaml/