1.1Go项目中配置文件相关之.ini

1.介绍

ini文件全称"initialization",文件后缀名为.ini

ini 文件格式用于保存相关软件的配置信息

2.原理

主要结构为包括以下的文本信息:

1.sections(段)

2.keys(properties\键)

3.values(值)


例如

1.sections

格式如下:

[section]

a=a

b=b


比如项目中



配置文件的目录

app.debug.ini

[app]

RuntimeRootPath =runtime/

LogSavePath =logs/

LogSaveName =xxx

LogFileExt =log

LogLevel =debug

TimeFormat =2006010215

ExpireDay =7

SentryDSN =""

InterfaceTimeOut =3

AnnounceURL =""

[server]

RunMode =release

HttpPort =8023

ReadTimeout =3

WriteTimeout =3

[mysql]

Type =mysql

User =""

Password =""

Host =xx.xx.x.x:xxx

DmsName =xxxxx

DmsTablePrefix =xxxx_

RecordName =xxxx_xxx_xxx

SmartHomeName =xx_xx_xx

SmartHomeTablePrefix =gmt_

DeviceDataName =xx_xx_xx



然后写个



package conf

import (

"fmt"

"github.com/go-ini/ini"

"gitlab.aiforward.cn/horus/golib/rclib"

"time"

)

//1.配置所有需要用到的结构体在这里创建

type App struct {

RuntimeRootPath string

  ImageSavePath  string

  ImageMaxSize  int

  ImageAllowExts []string

  ExportSavePath string

  QrCodeSavePath string

  FontSavePath  string

  LogSavePath            string

  LogSaveName            string

  LogFileExt              string

  LogLevel                string

  TimeFormat              string

  ExpireDay              int32

  SentryDSN              string

  AbsoluteImagePrefixPath string

  InterfaceTimeOut        int64

  DeviceListTmpFile      string

  DeviceListFile          string

  RegionProportion        string

  AnnounceURL            string

}

var AppSetting = &App{}

type Server struct {

RunMode      string

  HttpPort    int

  ReadTimeout  time.Duration

  WriteTimeout time.Duration

}

var ServerSetting = &Server{}

type PMSConfig struct {

BaseURL        string

  AppId          string

  AppSecretKey  string

  PMSTokenVerify string

  PMSStaffInfo  string

}

var PMSetting = &PMSConfig{}

type MysqlDatabase struct {

Type                string

  User                string

  Password            string

  Host                string

  DmsName              string

  DmsTablePrefix      string

  RecordName          string

  RecordTablePrefix    string

  SmartHomeName        string

  SmartHomeTablePrefix string

  DeviceDataName      string

}

var MysqlSetting = &MysqlDatabase{}

type Pgsql struct {

User          string

  Password      string

  Host          string

  Port          int

  DBName        string

  DBTablePrefix string

}

type Redis struct {

Host        string

  Password    string

  DB          int

  MaxIdle    int

  MaxActive  int

  IdleTimeout time.Duration

}

type Image struct {

BasePath        string

  BaseUrl          string

  FileType        string

  ComputeBasePath  string

  DockerPrefixPath string

  ComputeBaseUrl  string

  UrlPort          string

  DefaultHost      string

}

type Mqtt struct {

Server string

}

type Face struct {

Register string

}

type TenCent struct {

AppId          string

  SecretId        string

  SecretKey      string

  CosBucket      string

  CosRegion      string

  PublicCosBucket string

}

type Gms struct {

Host      string

  AppId    string

  AppSecret string

}

type RcPlanish struct {

Host      string

  AppId    string

  AppSecret string

}

type Community struct {

AppId              string

  AppSecretKey        string

  Host                string

  AnalysisUrl        string

  InoutStatisticsUrl  string

  StaticsUrl          string

  BuildingList        string

  RoomOverview        string

  RoomMember          string

  RosterRoomInfo      string

  RoomGet            string

  RoomList            string

  RoomModifyAdmin    string

  FloorList          string

  UnitList            string

  RoomAccessList      string

  LinkDeviceRoom      string

  ResidentGet        string

  ResidentAdd        string

  ResidentList        string

  ResidentDetail      string

  ResidentDelete      string

  ResidentModify      string

  ResidentEdit        string

  ResidentBindRoom    string

  ResidentMemberList  string

  StaffGet            string

  StaffAdd            string

  StaffList          string

  StaffModify        string

  StaffDelete        string

  StaffModifyPassword string

  CommunityGet        string

  DetailURL          string

  SipContact          string

  GetLocationURL      string

  LocationListURL    string

  LocationAllURL      string

  LocationTreeURL    string

  GetCommonURl        string

  CommunityAddress    string

  AccessAddress      string

  PropertyAddress    string

  AddressIds          string

  HouseAddress        string

  AccessStatistics    string

  UserDetail          string

}

type HealthCode struct {

Host            string

  HealthCodeColor string

}

// 数据上报服务控制

type DataReport struct {

OfflineTypes []int

}

type Kafka struct {

ServerIp      string

  GroupId        string

  TopicCommunity string

  TopicResident  string

  TopicStaff    string

  AutoOffset    string

}

type RongChuang struct {

PushHost    string

  AccessToken string

  PushAppInfo string

  AppId      string

  TokenSecret string

}

type Iot struct {

AccessProductId      string

  MethodQrUnlock        string

  MethodBluetoothUnlock string

  MethodIntercomUnlock  string

  MethodFixedUnlock    string

  MethodUpdateSecret    string

  ServerGrpc            string

  AppKey                string

  AppSecret            string

  PlainText            bool

}

type PMDS struct {

Host string

}

type CMDS struct {

Host string

}

type AlarmRobot struct {

Key string

}

type Pulsar struct {

Url string

}

//2.所有配置相关的全局变量在这里声明好

var PgsqlSetting = &Pgsql{}

var ImageSetting = &Image{}

var RedisSetting = &Redis{}

var MqttSetting = &Mqtt{}

var FaceSetting = &Face{}

var TencentSetting = &TenCent{}

var GmsSetting = &Gms{}

var CommunitySetting = &Community{}

var HealthCodeSetting = &HealthCode{}

var DataReportSetting = &DataReport{}

var RongChuangSetting = &RongChuang{}

var AlarmRobotSetting = &AlarmRobot{}

var IotSetting = &Iot{}

var PMDSSetting = &PMDS{}

var CMDSSetting = &CMDS{}

var RcAppSetting = &rclib.RcApp{}

var RcSeverSetting = &rclib.RcServer{}

var RcConfigSetting = &rclib.RcConfig{}

var KafkaSetting = &Kafka{}

var PulsarSetting = &Pulsar{}

var RcPlanishSetting = &RcPlanish{}

var cfg *ini.File

// Setupinitialize the configuration instance

//3.提供main读取配置文件的方法,初始化赋值conf的全局变量

func Setup(env string) {

var err error

  cfg,err =ini.Load(fmt.Sprintf("conf/app.%s.ini",env))

fmt.Println("Setup Config,  Parse File:",fmt.Sprintf("conf/app.%s.ini",env))

if err !=nil {

fmt.Println("setting.Setup, fail to parse 'conf/app.ini': %v",err)

}

mapTo("app",AppSetting)

mapTo("server",ServerSetting)

mapTo("mysql",MysqlSetting)

mapTo("pgsql",PgsqlSetting)

mapTo("redis",RedisSetting)

mapTo("image",ImageSetting)

mapTo("mqtt",MqttSetting)

mapTo("face",FaceSetting)

mapTo("tencent",TencentSetting)

mapTo("kafka",KafkaSetting)

mapTo("pms",PMSetting)

mapTo("gms",GmsSetting)

mapTo("community",CommunitySetting)

mapTo("healthcode",HealthCodeSetting)

mapTo("datareport",DataReportSetting)

mapTo("rongchuang",RongChuangSetting)

mapTo("iot",IotSetting)

mapTo("pmds",PMDSSetting)

mapTo("cmds",CMDSSetting)

mapTo("alarm_robot",AlarmRobotSetting)

mapTo("rcapp",RcAppSetting)

mapTo("rcserver",RcSeverSetting)

mapTo("pulsar",PulsarSetting)

mapTo("rcplanish",RcPlanishSetting)

RcConfigSetting.App = *RcAppSetting

  RcConfigSetting.Server = *RcSeverSetting

  AppSetting.ImageMaxSize =AppSetting.ImageMaxSize *1024 *1024

  ServerSetting.ReadTimeout =ServerSetting.ReadTimeout *time.Second

  ServerSetting.WriteTimeout =ServerSetting.WriteTimeout *time.Second

}

// mapTomap section

func mapTo(section string,v interface{}) {

err :=cfg.Section(section).MapTo(v)

if err !=nil {

fmt.Println("Cfg.MapTo %s err: %v",section,err)

}

}


这样全局都能读出来

你可能感兴趣的:(1.1Go项目中配置文件相关之.ini)