程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> PHP基礎知識 >> GoConf 簡單實用的Golang程序配置文件解析

GoConf 簡單實用的Golang程序配置文件解析

編輯:PHP基礎知識
 

GoConf是用於Go語言程序解析配置文件的小工具。

目前GoConf支持JSON格式配置文件,支持多層級的配置項,支持注釋,支持按層次路徑直接獲取配置項值。使用起來也非常簡單,我們來看個例子。
首先是配置文件 configure.json。由於注釋並不是JSON格式規范的一部分,但配置文件往往需要一些注釋輔助說明,因此GoConf提供了多行/**/和單行//注釋支持, 但要求注釋和配置項不能在同一行。配置項可以有多個層次,這是JSON格式配置文件較ini格式配置文件的優點,使得我們可以非常清晰有序地組織配置項。配置項的值可以是單個值,也可以是一個數組。
 

/* Configure comment
*/
{
/* ModuleA comment
*/
"ModuleA":{
/* SubModule1 comment
*/
"SubModule1":{
// Int example
"itemInt":2,
"itemIntArray":[1, 2, 3, 4, 5],
// Float example
"itemFloat":2.01,
"itemFloatArray":[1.1, 2.1, 3.1, 4.1, 5.1],
// String example
"itemString":"/home/abc/httpd.conf",
"itemStringArray":["admin1", "admin2"],
// Bool example
"itemBool": true
},
/* SubModule2 comment
*/
"SubModule2":{
// Object example
"ItemObject":{
"email":["[email protected]", "[email protected]"],
"sms":["130123456789", "150123456789"]
},
"ItemObjectArray":[
{"Listen":"127.0.0.1","Port":9000},
{"Listen":"127.0.0.2","Port":9001},
{"Listen":"127.0.0.3","Port":9002}
]
}
},
/* ModuleB comment
*/
"ModuleB":{
// your configure items
}
}
 

再來看看我們如何加載這樣一個配置文件

package goconf_test

import (
"fmt"

"github.com/pantsing/goconf"
)

func ExampleConfigLoadAndGet() {
// 首先,初始化並加載配置文件到變量c
c, err := goconf.New("configure.json")
if err != nil {
fmt.Println("Error:", err)
}

// 這裡我們定義一個struct用於存放一組多個配置項,Golang是一種靜態類型語言,數據類型的一致性要求非常嚴格,GoConf會將各配置項中JSON數據類型進行正確轉化後賦給struct中的相應字段,而無需我們逐一斷言判斷。
// Configure into struct
type ModuleAConf struct {
SubModule1 struct {
ItemInt int64
ItemIntArray []int64

ItemFloat float64
ItemFloatArray []float64

ItemString string
ItemStringArray []string

ItemBool bool
}
SubModule2 struct {
ItemObject struct {
Email []string
Sms []string
}
ItemObjectArray []struct {
Listen string
port uint16 // Unexported field can not receive configure item value
Port uint16
}
}
}
// 加載層次路徑“/ModuleA”下的全部配置項到我們定義的結構體ModuleAConf
itemModuleA := new(ModuleAConf)
c.Get("/ModuleA", itemModuleA)

fmt.Println(*itemModuleA)

// 我們也可以通過路徑直接讀取配置文件中任意一個配置項的值
// One item
itemIntArray := []int64{}
c.Get("/ModuleA/SubModule1/itemIntArray", &itemIntArray)

fmt.Println(itemIntArray)

// Output
// {{2 [1 2 3 4 5] 2 [1 2 3 4 5] /home/abc/httpd.conf [admin1 admin2] false} {{[[email protected] [email protected]] [130123456789 150123456789]} [{127.0.0.1 0 9000} {127.0.0.2 0 9001} {127.0.0.3 0 9002}]}}
// [1 2 3 4 5]
}

 

嗯,GoConf用起來就是這麼簡單。 你可以使用下面的命令來安裝他。有任何問題、需求、建議歡迎在github或這裡給我留言。

go get github.com/pantsing/goconf
 

 
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved