Golang專案中讀取配置檔案

奇蹟師發表於2021-06-16
  • 需要的知識(相對路徑”./“,”../“和”/“的區別)
    blog.csdn.net/qq_34769573/article/...
  • 專案目錄
    專案名
      |-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()
}

1.ini

github.com/go-ini/ini

2.yml

github.com/go-yaml/yaml/

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章