The read configuration file is used in the recent Go Language project as follows:
Use this "github.com/burntsushi/toml"
The configuration file is as follows: CONF.TOML
# id
id = 1
# name
name = "name1"
# weight
weight = 1.7
# books
books = ["A", "B", "C"]
Se x = True
#friend friend can be
[friend] Age
= +
Name = "Xio"
The code is as follows Readconf.go:
Package conf
Import (
"FMT",
"github.com/burntsushi/toml" "
io/ioutil" "
os"
)
/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 readconf (fname String) (p *person, err error) {
var (
fp *os. File
fcontent []byte
]
p = new (person)//&person{}
if fp, err = OS. Open (fname); Err! = Nil {
FMT. PRINTLN ("Open error", err)
return
}
if fcontent, err = Ioutil. ReadAll (FP); Err! = Nil {
FMT. PRINTLN ("ReadAll error", err)
return
}
If Err = toml. Unmarshal (Fcontent, p); Err! = Nil {
FMT. Println ("toml. Unmarshal error ", err)
return
}
return
}
The test code is as follows Readconf_test.go:
Package conf
Import "testing"
func testreadconf (t *testing. T) {
p, err: = Readconf ("./conf.toml")
if err! = Nil {
T.logf ("%v", Err)
}
t.logf ("Person%v", p)
t.logf ("Person.friend%v", P.friend)
}
The output is:
[' Go test-v ' | done:2.6748515s]
= = = RUN testreadconf
---pass:testreadconf (0.00s)
Readconf_test.go:11:person &{1 true name1 1.7 0x1218c570 [a b c]}
readconf_test.go:12:person.friend &{32 Xio}
PASS
OK goprogram/conf 0.458s
Detail point:
1 member of struct First capital letter
2 configuration items for configuration files must be the same as struct member names
3 supports bool, int, float, string, string array ... can also contain other structures such as [Friend]
Attached: Learning Links
Https://item.congci.com/-/content/toml-ji-jian-de-peizhiwenjian-geshi
Https://github.com/toml-lang/toml