Go language: How to read a configuration file toml

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.