当前位置:   article > 正文

Go 编程实例【Config.ini配置文件结构体配置】_config.ini文件内容如何编写

config.ini文件内容如何编写

config.ini 配置文件

[server]
ip=10.238.2.2
port = 8080

[mysql]
username=root
passwd = root
database = test
host=192.168.1.1
port=3066
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

ini_config_test.go 配置文件结构体

package iniconfig

import (
	"os"
	"testing"
)

// tag 对应 config.ini 名字
// 存储 ini 的 [server]、[mysql]
type Config struct {
	ServerConf ServerConfig `ini:"server"`
	MysqlConf  MysqlConfig  `ini:"mysql"`
}

// 配置项对应的值
type ServerConfig struct {
	IP   string `ini:"ip"`
	Port int    `ini:"port"`
}

// 配置项对应的值
type MysqlConfig struct {
	Username string `ini:"username"`
	Passwd   string `ini:"passwd"`
	Database string `ini:"database"`
	Host     string `ini:"host"`
	Port     int    `ini:"port"`
}

func TestIniConfig(t *testing.T) {
	// 读取 ini文件
	data, err := os.ReadFile("./config.ini")
	if err != nil {
		t.Error("read file failed")
	}

	// 定义结构体
	var conf Config
	err = UnMarshal(data, &conf)
	if err != nil {
		t.Errorf("unmarshal failed,err:%v", err)
	}
	// 打印调试日志
	t.Logf("unmarshal success,conf====:%#v", conf)
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45

单元测试打印初始化的结构体

PS D:\TEXT\gotest\iniconfig> go test -v
=== RUN   TestIniConfig

    ini_config_test.go:47: unmarshal success,conf====:
    
    iniconfig包名,Config配置文件结构体名称。
    iniconfig.Config{
    	ServerConf结构体字段,iniconfig包名ServerConfig结构体
    	ServerConf:iniconfig.ServerConfig{IP:"", Port:0}, 
   	    MysqlConf:iniconfig.MysqlConfig{Username:"", Passwd:"", Database:"", Host:"", Port:0}
    }
    
--- PASS: TestIniConfig (0.00s)
PASS
ok      gotest/iniconfig        0.184s
PS D:\TEXT\gotest\iniconfig> 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

ini_config.go 获取数据和结构体

package iniconfig

import (
	"errors"
	"reflect"
)

func UnMarshal(data []byte, result interface{}) (err error) {
	// 字符切片,通过换行符分割
	//lineArr := strings.Split(string(data), "\n")
	// 遍历打印 ini 文件的的数据,通过换行符进行拆分。
	//for _, v := range lineArr {
	//	fmt.Printf("%s\n", v)
	//}

	// 获取用户传递数据类型
	typeInfo := reflect.TypeOf(result)
	// typeInfo.Kind() 类型名称
	// reflect.Ptr 指向某个类型的指针类型
	// 判断 result 是否为指针类型,如果不是指针类型则返回错误。
	if typeInfo.Kind() != reflect.Ptr {
		err = errors.New("please pass address")
		return
	}
	return
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/84008
推荐阅读
相关标签
  

闽ICP备14008679号