• golang几种常用配置文件使用方法总结(yaml、toml、json、xml、ini)


    1,yaml配置文件的使用方法总结

    首先介绍使用yaml配置文件,这里使用的是github上第三方开源   gopkg.in/yaml.v2
    第一步:下载

    go get gopkg.in/yaml.v21
    import "gopkg.in/yaml.v2"

    第二步:新建一个yaml文件,比如conf.yaml

    host: localhost:3306
    user: tigerwolfc
    pwd: 654321
    dbname: tablename

    特别需要强调的是冒号后面必须有一个空格,以user: tigerwolfc为例,

    user: tigerwolfc//冒号后面有空格

     第三步:在程序中使用配置文件获取参数,比如main.go

    package main
    
    import (
        "io/ioutil"
        "gopkg.in/yaml.v2"
        "fmt"
    )
    
    func main() {
       var c conf
       conf:=c.getConf()
       fmt.Println(conf.Host)
    }
    
    //profile variables
    type conf struct {
        Host string `yaml:"host"`
        User string `yaml:"user"`
        Pwd string `yaml:"pwd"`
        Dbname string `yaml:"dbname"`
    }
    func (c *conf) getConf() *conf {
        yamlFile, err := ioutil.ReadFile("conf.yaml")
        if err != nil {
            fmt.Println(err.Error())
        }
        err = yaml.Unmarshal(yamlFile, c)
        if err != nil {
            fmt.Println(err.Error())
        }
        return c
    }

    运行main.go,就可以打印出配置文件中user的值tigerwolfc

    2,toml配置文件的使用方法总结

    TOML 的目标是成为一个极简的配置文件格式。TOML 被设计成可以无歧义地被映射为哈希表,从而被多种语言解析。需要使用第三方库https://github.com/BurntSushi/toml
    第一步:下载

    go get github.com/BurntSushi/toml

    第二部:新建一个toml文件,比如conf.toml

    # id
    ID = 3
    # name
    Name = "TigerwolfC"
    # weight
    Weight = 58
    # books
    Books = ["Golang", "C++", "Python"]
    Sex = true
    #friend Friend都可以
    [friend]
    Age = 28
    Name = "chen_peggy"

    细节点:

      • 结构体的成员首字母大写
      • 配置文件的配置项须与结构体成员名一样
      • 支持bool, int, float , 字符串,字符串数组…等,也可以包含其他结构体 如[Friend]
        第三步:在程序中使用配置文件
    package main
    import (
        "fmt"
        "github.com/BurntSushi/toml"
        "log"
    )
    //Person
    type Person struct {
        ID     uint32    
        Sex    bool    
        Name   string    
        Weight float32    
        Friend *Friends    
        Books  []string
    } 
        
    // friends
    type Friends struct {    
        Age  int    
        Name string
    }
    
    func test_toml() {
        var cp Person
        var path string = "./conf.toml"
        if _, err := toml.DecodeFile(path, &cp); err != nil {
            log.Fatal(err)
        }
        fmt.Printf("%v %v
    ", cp.Name, cp.Friend.Name)
    }
    func main() {
        test_toml()
    }
    
    /*
    result:
    TigerwolfC  chen_peggy
     */

    2,

    package  main
    
    import (
        "fmt"
        "github.com/BurntSushi/toml"
    )
    
    //订制配置文件解析载体
    type Config struct{
        Database *Database
        SQL *SQL
    }
    
    //订制Database块
    type Database struct {
        Driver    string
        Username  string `toml:"us"` //表示该属性对应toml里的us
        Password string
    }
    //订制SQL语句结构
    type SQL struct{
        Sql1 string `toml:"sql_1"`
        Sql2 string `toml:"sql_2"`
        Sql3 string `toml:"sql_3"`
        Sql4 string `toml:"sql_4"`
    }
    
    var config *Config=new (Config)
    func init(){
        //读取配置文件
        _, err := toml.DecodeFile("test.toml",config)
        if err!=nil{
            fmt.Println(err)
        }
    }
    func main() {
          fmt.Println(config)
          fmt.Println(config.Database)
          fmt.Println(config.SQL.Sql1)
    }
    #This file as Config struct
    
    #this block as Database struct
    [Database]
    driver="jdbc:mysql.jdbc.Driver"
    us="ft"
    password="123"
    
    #this block as SQL struct
    [SQL]
    sql_1= "select * from user"
    sql_2="updata user set name = 'exo'"
    sql_3="delete * from user"
    sql_4="Insert into user(id,name) values(5,'ft')"

    3,json配置文件的使用方法总结

    JSON(JavaScript Object Notation, JS 对象标记) 是一种轻量级的数据交换格式。简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。
    新建一个文件名为conf.json,键入内容:

    {
        "enabled": true,
        "path": "/usr/local"
    }

    新建main.go,键入内容:

    package main
    import (
        "encoding/json"
        "fmt"
        "os"
    )
    
    type configuration struct {
        Enabled bool
        Path    string
    }
    
    func main() {
        file, _ := os.Open("conf.json")
        defer file.Close()
        decoder := json.NewDecoder(file)
        conf := configuration{}
        err := decoder.Decode(&conf)
        if err != nil {
            fmt.Println("Error:", err)
        }
        fmt.Println(conf.Path)
    }

    4,xml配置文件的使用方法总结

    可扩展标记语言,标准通用标记语言的子集,是一种用于标记电子文件使其具有结构性的标记语言。
    新建一个文件名为conf.xml,键入内容:

    <?xml version="1.0" encoding="UTF-8" ?>
    <Config>
       <enabled>true</enabled>
       <path>/usr/local</path>
    </Config>

    新建main.go,键入内容:

    package main
    import (
        "encoding/xml"
        "fmt"
        "os"
    )
    type configuration struct {
        Enabled bool   `xml:"enabled"`
        Path    string `xml:"path"`
    }
    func main() {
        xmlFile, err := os.Open("conf.xml")
        if err != nil {
            fmt.Println("Error opening file:", err)
            return
        }
        defer xmlFile.Close()
        var conf configuration
        if err := xml.NewDecoder(xmlFile).Decode(&conf); err != nil {
            fmt.Println("Error Decode file:", err)
            return
        }
        fmt.Println(conf.Enabled)
        fmt.Println(conf.Path)
    }

    5,ini配置文件的使用方法总结

    INI文件格式是某些平台或软件上的配置文件的非正式标准,以节(section)和键(key)构成,常用于微软Windows操作系统中。这种配置文件的文件扩展名多为INI,故名。
    新建一个文件名为conf.ini,键入内容:

    ; A comment line
    [Section]
    enabled = true
    path = /usr/local # another comment

    使用第三方库:

    go get gopkg.in/gcfg.v1

    新建main.go,键入代码:

    package main
    import (
        "fmt"
        "gopkg.in/gcfg.v1"
    )
    func main() {
        config := struct {
            Section struct {
                Enabled bool
                Path    string
            }
        }{}
        err := gcfg.ReadFileInto(&config, "conf.ini")
        if err != nil {
            fmt.Println("Failed to parse config file: %s", err)
        }
        fmt.Println(config.Section.Enabled)
        fmt.Println(config.Section.Path)
    }

    原文链接:https://blog.csdn.net/wade3015/article/details/83351776

  • 相关阅读:
    unity对于导入动画不可编辑的添加事件函数方式
    unity创建Animation动画文件
    unity之3dmax建模(人物模型)注意细节
    unity导入fbx文件并播放模型动画
    Java网络编程:QQ邮件发送客户端程序设计
    Java进阶:基于TCP通信的网络实时聊天室
    如何开发HTML编辑器
    分布式redislock使用注意事项
    《MySQL慢查询优化》之数据库表结构优化
    《MySQL慢查询优化》之慢SQL日志获取与分析
  • 原文地址:https://www.cnblogs.com/sunlong88/p/11983583.html
Copyright © 2020-2023  润新知