小智 6
您可以使用以下代码而不是使用 3rd Party 库
package main
import (
"bufio"
"fmt"
"io"
"os"
"strings"
)
type Config map[string]string
func ReadConfig(filename string) (Config, error) {
// init with some bogus data
config := Config{
"port": "8888",
"password": "abc123",
"ip": "127.0.0.1",
}
if len(filename) == 0 {
return config, nil
}
file, err := os.Open(filename)
if err != nil {
return nil, err
}
defer file.Close()
reader := bufio.NewReader(file)
for {
line, err := reader.ReadString('\n')
// check if the line has = sign
// and process the line. Ignore the rest.
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:])
}
// assign the config map
config[key] = value
}
}
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
}
return config, nil
}
func main() {
// for this tutorial, we will hard code it to config.txt
config, err := ReadConfig(`C:\Users\mseelam.ORADEV\GoglandProjects\MyFirstProj\data\config`)
if err != nil {
fmt.Println(err)
}
//fmt.Println("Config data dump :", config)
// assign values from config file to variables
ip := config["ip"]
pass := config["pass"]
port := config["port"]
fmt.Println("IP :", ip)
fmt.Println("Port :", port)
fmt.Println("Password :", pass)
}
Run Code Online (Sandbox Code Playgroud)
除了@Madhu的答案之外,您可以创建一个非常简单的程序包,以使用Scanner读取属性文件,并逐行读取文件,跳过无效的行(不包含'='字符的行):
例:
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
}
Run Code Online (Sandbox Code Playgroud)
样本测试sample_test.properties:
host=localhost
proxyHost=test
protocol=https://
chunk=
Run Code Online (Sandbox Code Playgroud)
性能测试:
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")
}
}
Run Code Online (Sandbox Code Playgroud)
从您的问题来看,不清楚您是要解析一些现有的属性文件,还是仅对让 Go 程序使用以某种文本形式呈现的配置的一般方法感兴趣。
如果你想要前者,那么@icza就给你指明了正确的方向:至少存在一个 3rd-party Go 包,它实现了 Java 属性文件的解析。
如果你想要后者,有很多解决方案可供选择:
标准库包含用于解析 XML 和 JSON 格式的数据流的包。
存在许多用于读取 INI 样式文件的第 3 方库。存在一个库,它允许读取带有嵌套部分(Git 配置样式)的“分层”INI 文件。
存在解析自定义文本格式的第 3 方库,例如 YAML 和 TOML。
最后,存在“集成”解决方案,可以同时从不同来源提取配置位:环境、配置文件和命令行选项;https://github.com/spf13/viper就是一个很好的例子。
TL; 博士
仔细考虑你的目标,做你的研究,选择你的选择。
如果您的属性文件使用TOML ,那么您可以使用https://github.com/BurntSushi/toml中的 TOML 解析器 。这是我做的一个示例,它为我解析“属性文件” 属性文件内容(properties.ini)
dbpassword="password"
database="localhost"
dbuser="user"
Run Code Online (Sandbox Code Playgroud)
解析属性文件的代码
package main
import (
"fmt"
"log"
"os"
"github.com/BurntSushi/toml"
)
// Config ...
type Config struct {
Dbpassword string
Database string
DbUser string
}
// Reads info from config file
func ReadConfig() Config {
var configfile = "properties.ini"
_, err := os.Stat(configfile)
if err != nil {
log.Fatal("Config file is missing: ", configfile)
}
var config Config
if _, err := toml.DecodeFile(configfile, &config); err != nil {
log.Fatal(err)
}
//log.Print(config.Index)
return config
}
func main() {
config := ReadConfig()
fmt.Printf("%s: %s: %s\n", config.Dbpassword, config.Database, config.DbUser)
}
Run Code Online (Sandbox Code Playgroud)
输出:
password: localhost: user
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10810 次 |
| 最近记录: |