Go语言读取配置文件

原文地址:http://blog.csdn.net/fwhezfwhez/article/details/79170645

读取配置文件

config.go

package conf

import (
    "bufio"
    "io"
    "os"
    "strings"
)

func InitConfig(path string) map[string]string {
    //初始化
    myMap := make(map[string]string)

    //打开文件指定目录,返回一个文件f和错误信息
    f, err := os.Open(path)

    //异常处理 以及确保函数结尾关闭文件流
    if err != nil {
        panic(err)
    }
    defer f.Close()

    //创建一个输出流向该文件的缓冲流*Reader
    r := bufio.NewReader(f)
    for {
        //读取,返回[]byte 单行切片给b
        b, _, err := r.ReadLine()
        if err != nil {
            if err == io.EOF {
                break
            }
            panic(err)
        }

        //去除单行属性两端的空格
        s := strings.TrimSpace(string(b))
        //fmt.Println(s)

        //判断等号=在该行的位置
        index := strings.Index(s, "=")
        if index < 0 {
            continue
        }
        //取得等号左边的key值,判断是否为空
        key := strings.TrimSpace(s[:index])
        if len(key) == 0 {
            continue
        }

        //取得等号右边的value值,判断是否为空
        value := strings.TrimSpace(s[index+1:])
        if len(value) == 0 {
            continue
        }
        //这样就成功吧配置文件里的属性key=value对,成功载入到内存中c对象里
        myMap[key] = value
    }
    return myMap
}

main.go

package main

import (
    "conf"
    "fmt"
)

func main() {
    //导入配置文件
    configMap := conf.InitConfig("src/db_configuration.txt")
    //获取配置里host属性的value
    fmt.Println(configMap["host"])
    //查看配置文件里所有键值对
    fmt.Println(configMap)
}

db_configuration.txt

host=localhost
port=5432
user=postgres
passwor=123
dbname=test

结果:

localhost

map[port:5432 user:postgres passwor:123 dbname:test host:localhost]
注: 值得注意的是:路径可以写绝对路径和相对路径,即db_configuration.txt的位置如果是放在工程下和src同级,则”src/db_configuration.txt”,如果放在随便一个地方,就得写全路径”G:\java_workspace\test_config\src\db_configuration.txt”,斜杠要转义 
其实/和\等价,左斜杠不需要转义

猜你喜欢

转载自blog.csdn.net/qq_21794823/article/details/79653856