golang加载配置文件之toml配置

502 阅读1分钟

golang加载配置之toml配置:需要依赖第三方包,使用起来也比较简单,话不多说直接上干货

下载第三方包

go get github.com/BurntSushi/toml

config.toml

APP_NAME = "my_project"
Env = ["dev", "test", "product"]

[app]
Path = "/www/root"

[mysql]
Host = "127.0.0.1"
Name = "root"
Password = "123456"
Port = 3306

main.go

package main

import (
   "fmt"
   "github.com/BurntSushi/toml"
   "log"
)

type Config struct {
   AppName string `toml:"APP_NAME"`
   Env     []string
   App     *App
   Mysql   *Mysql
}

type App struct {
   Path string
}

type Mysql struct {
   Host     string
   Name     string
   Password string
   Port     int16
}

func main() {
   var c Config
   if _, err := toml.DecodeFile("./config.toml", &c); err != nil {
      log.Fatal(err)
      return
   }
   fmt.Printf("%s, %v, %v, %v", c.AppName, c.Env, c.App, c.Mysql)
}