• go读取yaml,json,ini等配置文件


    实际项目中,要读取一些json等配置文件。今天就来说一说,Golang 是如何读取YAML,JSON,INI等配置文件的。

    一. go读取json配置文件

    JSON 应该比较熟悉,它是一种轻量级的数据交换格式。层次结构简洁清晰 ,易于阅读和编写,同时也易于机器解析和生成。

    • 1.创建 conf.json:
    1. {
    2. "enabled": true,
    3. "path": "/usr/local"
    4. }
    • 2.新建config_json.go:
    1. package main
    2. import (
    3. "encoding/json"
    4. "fmt"
    5. "os"
    6. )
    7. type configuration struct {
    8. Enabled bool
    9. Path string
    10. }
    11. func main() {
    12. // 打开文件
    13. file, _ := os.Open("conf.json")
    14. // 关闭文件
    15. defer file.Close()
    16. //NewDecoder创建一个从file读取并解码json对象的*Decoder,解码器有自己的缓冲,并可能超前读取部分json数据。
    17. decoder := json.NewDecoder(file)
    18. conf := configuration{}
    19. //Decode从输入流读取下一个json编码值并保存在v指向的值里
    20. err := decoder.Decode(&conf)
    21. if err != nil {
    22. fmt.Println("Error:", err)
    23. }
    24. fmt.Println("path:" + conf.Path)
    25. }

    启动运行后,输出如下:

    1. D:\Go_Path\go\src\configmgr>go run config_json.go
    2. path:/usr/local

    1.2 复杂json解析

    假设test.json内容如下,如何解析?

    1. {
    2. "pids":{
    3. "default":{
    4. "pid":"1844_71935560",
    5. "desc":"app1"
    6. },
    7. "shehui":{
    8. "pid":"1844_101751664",
    9. "desc":"app2"
    10. }
    11. },
    12. "top_words":[
    13. "邓紫棋",
    14. "沈腾",
    15. "关晓彤",
    16. "鹿晗"
    17. ]
    18. }

    通过json转struct工具转换:

    Golang: Convert JSON to Struct

    JSON-to-Go: Convert JSON to Go instantly

    转化后的struct

    1. type configuration struct {
    2. Pids struct {
    3. Default struct {
    4. Pid string `json:"pid"`
    5. Desc string `json:"desc"`
    6. } `json:"default"`
    7. Shehui struct {
    8. Pid string `json:"pid"`
    9. Desc string `json:"desc"`
    10. } `json:"shehui"`
    11. } `json:"pids"`
    12. TopWords []string `json:"top_words"`
    13. }

    demo实现:

    1. package main
    2. import (
    3. "encoding/json"
    4. "fmt"
    5. "os"
    6. )
    7. type configuration struct {
    8. Pids struct {
    9. Default struct {
    10. Pid string `json:"pid"`
    11. Desc string `json:"desc"`
    12. } `json:"default"`
    13. Shehui struct {
    14. Pid string `json:"pid"`
    15. Desc string `json:"desc"`
    16. } `json:"shehui"`
    17. } `json:"pids"`
    18. TopWords []string `json:"top_words"`
    19. }
    20. func parseJsonConfig(filepath string) (conf configuration) {
    21. // 打开文件
    22. file, _ := os.Open(filepath)
    23. // 关闭文件
    24. defer file.Close()
    25. conf = configuration{}
    26. //NewDecoder创建一个从file读取并解码json对象的*Decoder,解码器有自己的缓冲,并可能超前读取部分json数据。
    27. //Decode从输入流读取下一个json编码值并保存在v指向的值里
    28. err := json.NewDecoder(file).Decode(&conf)
    29. if err != nil {
    30. fmt.Println("Error:", err)
    31. }
    32. return
    33. }
    34. func main() {
    35. pdd := parseJsonConfig("D:\\LearnGo\\FirstGo\\10-文件操作\\test3.json")
    36. fmt.Println(pdd)
    37. fmt.Println(pdd.Pids.Shehui.Pid)
    38. }

    再继续来个案例:

    假设json文件内容如下,想读取top_words中name的值,要怎么解析获取?

    1. {
    2. "pids":{
    3. "default":{
    4. "pid":"1844_71935560",
    5. "desc":"app1"
    6. },
    7. "shehui":{
    8. "pid":"1844_101751664",
    9. "desc":"app2"
    10. }
    11. },
    12. "top_words":[
    13. {
    14. "name": "cc",
    15. "age": 18
    16. },
    17. {
    18. "name": "test",
    19. "age": 20
    20. }
    21. ]
    22. }

    demo实现

    1. package main
    2. import (
    3. "encoding/json"
    4. "fmt"
    5. "os"
    6. )
    7. type configuration1 struct {
    8. Pids struct {
    9. Default struct {
    10. Desc string `json:"desc"`
    11. Pid string `json:"pid"`
    12. } `json:"default"`
    13. Shehui struct {
    14. Desc string `json:"desc"`
    15. Pid string `json:"pid"`
    16. } `json:"shehui"`
    17. } `json:"pids"`
    18. TopWords []struct {
    19. Age int64 `json:"age"`
    20. Name string `json:"name"`
    21. } `json:"top_words"`
    22. }
    23. func parseJsonConfig1(filepath string) (conf configuration1) {
    24. // 打开文件
    25. file, _ := os.Open(filepath)
    26. // 关闭文件
    27. defer file.Close()
    28. conf = configuration1{}
    29. //NewDecoder创建一个从file读取并解码json对象的*Decoder,解码器有自己的缓冲,并可能超前读取部分json数据。
    30. //Decode从输入流读取下一个json编码值并保存在v指向的值里
    31. err := json.NewDecoder(file).Decode(&conf)
    32. if err != nil {
    33. fmt.Println("Error:", err)
    34. }
    35. return
    36. }
    37. func main() {
    38. pdd := parseJsonConfig1("D:\\LearnGo\\FirstGo\\10-文件操作\\test4.json")
    39. fmt.Println(pdd)
    40. //遍历string切片获取name的值
    41. for _, i := range pdd.TopWords {
    42. name := i.Name
    43. fmt.Println(name)
    44. }
    45. }

    运行结果:

    1. {{{app1 1844_71935560} {app2 1844_101751664}} [{18 cc} {20 test}]}
    2. cc
    3. test

    最后一个工作用到的案例:读取json文件中的规则,做正则匹配,这里没有进行匹配操作,后续用到加上

    1. {
    2. "reverse_shell_rule":[
    3. {
    4. "id":"R10000",
    5. "regex":"socat\\s+TCP4:\\w+\\.\\w+\\.\\w+\\.\\w+:(\\w+)\\s+.*"
    6. },
    7. {
    8. "id":"R10001",
    9. "regex":"exec\\s+\\d+\\<\\>\/\\w+\/.*"
    10. }
    11. ]
    12. }

    1. // 读取JSON文件 将内容转为结构对象 然后更改数据
    2. package main
    3. import (
    4. "encoding/json"
    5. "fmt"
    6. "io/ioutil"
    7. )
    8. type ReverseJson struct {
    9. ReverseShellRule []struct {
    10. ID string `json:"id"`
    11. Regex string `json:"regex"`
    12. } `json:"reverse_shell_rule"`
    13. }
    14. func main() {
    15. var data ReverseJson
    16. // 读取JSON文件内容 返回字节切片
    17. bytes, _ := ioutil.ReadFile("D:\\LearnGo\\FirstGo\\10-文件操作\\test.json")
    18. // 打印时需要转为字符串
    19. fmt.Println(string(bytes))
    20. // 将字节切片映射到指定结构上
    21. json.Unmarshal(bytes, &data)
    22. //fmt.Println("*** unmarshal result: ***")
    23. // 打印对象结构
    24. for _, reg := range data.ReverseShellRule {
    25. rule := reg.Regex
    26. fmt.Println(rule)
    27. }
    28. }

    二、 go读取.ini配置文件

    INI文件格式是某些平台或软件上的配置文件的非正式标准,由节(section)和键(key)构成,比较常用于微软Windows操作系统中。这种配置文件的文件扩展名为INI。

    • 1.创建 conf.ini:
    1. [Section]
    2. enabled = true
    3. path = /usr/local # another comment
    • 2.下载第三方库:go get gopkg.in/gcfg.v1
    • 3.新建 config_ini.go:
    1. package main
    2. import (
    3. "fmt"
    4. gcfg "gopkg.in/gcfg.v1"
    5. )
    6. func main() {
    7. config := struct {
    8. Section struct {
    9. Enabled bool
    10. Path string
    11. }
    12. }{}
    13. err := gcfg.ReadFileInto(&config, "conf.ini")
    14. if err != nil {
    15. fmt.Println("Failed to parse config file: %s", err)
    16. }
    17. fmt.Println(config.Section.Enabled)
    18. fmt.Println(config.Section.Path)
    19. }

    启动运行后,输出如下:

    1. D:\Go_Path\go\src\configmgr>go run config_ini.go
    2. true
    3. /usr/local

    三、go读取yaml配置文件

    yaml 可能比较陌生一点,但是最近却越来越流行,尤其在SpringBoot中的application.yml或者application.yaml中使用非常广泛。也就是一种标记语言。层次结构也特别简洁清晰 ,易于阅读和编写,同时也易于机器解析和生成。

    golang的标准库中暂时没有给我们提供操作yaml的标准库,但是github上有很多优秀的第三方库开源给我们使用。

      1. 创建 conf.yaml:
    1. enabled: true
    2. path: /usr/local
    • 2.下载第三方库:go get gopkg.in/yaml.v2
    • 3.创建 config_yaml.go:
    1. package main
    2. import (
    3. "fmt"
    4. "io/ioutil"
    5. "log"
    6. "gopkg.in/yaml.v2"
    7. )
    8. type conf struct {
    9. Enabled bool `yaml:"enabled"` //yaml:yaml格式 enabled:属性的为enabled
    10. Path string `yaml:"path"`
    11. }
    12. func (c *conf) getConf() *conf {
    13. yamlFile, err := ioutil.ReadFile("conf.yaml")
    14. if err != nil {
    15. log.Printf("yamlFile.Get err #%v ", err)
    16. }
    17. err = yaml.Unmarshal(yamlFile, c)
    18. if err != nil {
    19. log.Fatalf("Unmarshal: %v", err)
    20. }
    21. return c
    22. }
    23. func main() {
    24. var c conf
    25. c.getConf()
    26. fmt.Println("path:" + c.Path)
    27. }

    启动运行后,输出如下:

    1. D:\Go_Path\go\src\configmgr>go run config_yaml.go
    2. path:/usr/local

    最后 以上,就把golang 读取配置文件的方法,都介绍完了。大家可以拿着代码运行起来看看。

    参考资料:

    Go 语言解析 JSON 文件 - 知乎 Go 语言解析 JSON 文件(推荐)

    如何读取yaml,json,ini等配置文件【Golang 入门系列九】-腾讯云开发者社区-腾讯云

  • 相关阅读:
    Get、Post的区别------重定向和转发的区别-----http、https的区别!!!
    mysql 在eclipse在配置
    【TA-霜狼_may-《百人计划》】图形5.1 PBR基础 BRDF介绍
    python连接mysql数据库的练习
    怎样用读写锁快速实现一个缓存?
    Springboot新增文章
    2024年的云原生架构需要哪些技术栈
    PMSM FOC位置环S曲线控制算法(恒定急动度)
    Python基础与应用代码
    线程的“结束”
  • 原文地址:https://blog.csdn.net/XCC_java/article/details/132606734