ini File Parser in Golang

392 阅读1分钟

There exists a package named ini which can be used to parse ini format file like below,

#
2458194803.tauth_token="111111"
#
2458194803.tauth_token_secret="111222"

Here is an example to do that,

package main

import (
	"fmt"

	"gopkg.in/ini.v1"
)

func main() {
	cfg, _ := ini.Load("test.ini")

	tokenKey := fmt.Sprintf("%s.tauth_token", "2458194803")
	secretKey := fmt.Sprintf("%s.tauth_token_secret", "2458194803")
	token := cfg.Section("").Key(tokenKey).String()
	secret := cfg.Section("").Key(secretKey).String()
	fmt.Println(token, secret)
}

But one day i encountered one problem in my program that could not be found easily, the code above printed truncated value, the test.ini file like below,

#
2458194803.tauth_token="OX##PRSVOWRVNQXNXONYUQYOQYOVRXOTRSQPTONVXNXNXJbadEQ8B#A"
#
2458194803.tauth_token_secret="ccc"

The code above generates output as below,

"OX ccc

The value is truncated, considering the sharp mark is used as comment mark in ini file, the problem may have something to do with it. Aftering some searching, I found the LoadSources method of ini package which includes an option argument that can be used to indicate whether or not ignore the sharp mark in value. Here is the working code,

package main

import (
	"fmt"

	"gopkg.in/ini.v1"
)

func main() {
        //Here is the method with options 
	cfg, _ := ini.LoadSources(ini.LoadOptions{IgnoreInlineComment: true}, "test.ini")

	tokenKey := fmt.Sprintf("%s.tauth_token", "2458194803")
	secretKey := fmt.Sprintf("%s.tauth_token_secret", "2458194803")
	token := cfg.Section("").Key(tokenKey).String()
	secret := cfg.Section("").Key(secretKey).String()
	fmt.Println(token, secret)
}

Now the output works as expected,

OX##PRSVOWRVNQXNXONYUQYOQYOVRXOTRSQPTONVXNXNXJbadEQ8B#A ccc