在golang中解析属性文件中的值 [英] parsing values from property file in golang
本文介绍了在golang中解析属性文件中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于Java,有一个Properties类,该类提供了用于解析属性文件或与属性文件进行交互的功能.
For Java there is the Properties class that offers functionality to parse / interact with property file.
golang标准库中是否有类似内容?
Is there something similar in golang standard library ?
如果没有,我还有什么其他选择?
If not, what other alternatives do I have ?
推荐答案
在@Madhu的答案的基础上,您可以创建一个非常简单的程序包以使用Scanner读取属性文件,并逐行读取跳过无效的文件行(没有'='字符的行):
Adding on top of @Madhu's answer, you can create a very simple package to read a properties file using Scanner, and read line by line of your file skipping invalid lines (those not having the '=' char):
示例:
package fileutil
import (
"bufio"
"os"
"strings"
"log"
)
type AppConfigProperties map[string]string
func ReadPropertiesFile(filename string) (AppConfigProperties, error) {
config := AppConfigProperties{}
if len(filename) == 0 {
return config, nil
}
file, err := os.Open(filename)
if err != nil {
log.Fatal(err)
return nil, err
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
if equal := strings.Index(line, "="); equal >= 0 {
if key := strings.TrimSpace(line[:equal]); len(key) > 0 {
value := ""
if len(line) > equal {
value = strings.TrimSpace(line[equal+1:])
}
config[key] = value
}
}
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
return nil, err
}
return config, nil
}
样本测试sample_test.properties:
Sample test sample_test.properties :
host=localhost
proxyHost=test
protocol=https://
chunk=
属性测试:
package fileutil
import (
"testing"
)
func TestReadPropertiesFile(t *testing.T) {
props, err := ReadPropertiesFile("sample_test.properties")
if err != nil {
t.Error("Error while reading properties file")
}
if props["host"] != "localhost" || props["proxyHost"] != "test" || props["protocol"] != "https://" || props["chunk"] != "" {
t.Error("Error properties not loaded correctly")
}
}
这篇关于在golang中解析属性文件中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文