GoLang 使用goconfig读取配置文件(.ini、.json、.yaml)

it2024-12-26  9

一、goconfig读取.ini类型配置文件

1、配置文件(config.ini)如下:

[RabbitMQ] MQUrl = amqp://trkj:trkj@192.168.5.62:5672/test Exchange = EX.WALLDATA ExchangeType = fanout RoutingKey = RK.WALLDATA [Base] messageFrequency = 5

2、解析配置文件:

package main import ( "fmt" "github.com/hyahm/goconfig" ) type RabbitMQ struct { MQUrl string Exchange string ExchangeType string RoutingKey string } type BaseConfig struct { MsgFrequency int64 // 消息发送频率 RabbitMQ // MQ信息 } func ReadBaseConfig(bconfig *BaseConfig, confFile string) { goconfig.InitConf(confFile, goconfig.INI) bconfig.MsgFrequency = goconfig.ReadInt64("Base.messageFrequency", 3) bconfig.RabbitMQ.MQUrl = goconfig.ReadString("RabbitMQ.MQUrl", "") bconfig.RabbitMQ.Exchange = goconfig.ReadString("RabbitMQ.Exchange", "") bconfig.RabbitMQ.ExchangeType = goconfig.ReadString("RabbitMQ.ExchangeType", "") bconfig.RabbitMQ.RoutingKey = goconfig.ReadString("RabbitMQ.RoutingKey", "") } func main() { baseConfig := BaseConfig{} ReadBaseConfig(&baseConfig, "./Config.ini") fmt.Printf("mq.MQUrl = %s \t mq.Exchange = %s \t mq.ExchangeType = %s \t mq.RoutingKey = %s\n", baseConfig.RabbitMQ.MQUrl, baseConfig.RabbitMQ.Exchange, baseConfig.RabbitMQ.ExchangeType, baseConfig.RabbitMQ.RoutingKey) fmt.Printf("msgFrequency = %d\n", baseConfig.MsgFrequency) }

 

 

 

 

 

最新回复(0)