技术控

    今日:0| 主题:63445
收藏本版 (1)
最新软件应用技术尽在掌握

[其他] Code: Simple config file reader for Golang applications

[复制链接]
海岛陌安逝暮梦 发表于 2016-12-2 07:24:44
139 2
Simple config file reader for Golang applications

  Ordinary users forget quotes, separators, braces and don't want to learn syntax of json, xml, yaml, toml, whateverML to create or edit config files.
  Installation:

  1. go get github.com/is73/cfg
复制代码
Test:

  1. go test github.com/is73/cfg
复制代码
Config file example:

  
       
  • First word on line is a key name, can't contain white space   
  • Sections can be emulated using key prefix   
  • Key duplicity is not allowed   
  • Any white space after first word, space or tab (even multiple), is a key value separator   
  • Anything after separator except new line character is the value of the key   
  • Values may contain white space characters   
  • Lines without value are ignored   
  • Empty lines are ignored  
  1. # this is a comment line
  2. # file contains intentional spaces and tabs
  3. key1 value1
  4. key2    value2
  5. key3        value3 value3   value3
  6. # next line is ignored, value is missing
  7. keynoval
  8. user.id 1
  9. user.name john
  10. user.surname doe
  11. # next empty line is ignored
  12. smtp_server     smtp.example.com
  13. smtp_port       25
  14. smtp_user       [email protected]
  15. smtp_password       harDtoGueSs
复制代码
Seeconfig.txt in examples  
  Reading config file:

  1. package main
  2. import (
  3.     "fmt"
  4.     "github.com/is73/cfg"
  5. )
  6. func main() {
  7.     fmt.Println("Output, prefix unused:")
  8.     config, err := cfg.Read("config.txt", "")
  9.     if err != nil {
  10.         fmt.Println(err)
  11.     }
  12.     for k, v := range config {
  13.         fmt.Printf("'%s':'%s'\n", k, v)
  14.     }
  15.     fmt.Println("\nOutput, prefix used:")
  16.     config, err = cfg.Read("config.txt", "user.")
  17.     if err != nil {
  18.         fmt.Println(err)
  19.     }
  20.     for k, v := range config {
  21.         fmt.Printf("'%s':'%s'\n", k, v)
  22.     }
  23. }
  24. /*
  25. Output, prefix unused:
  26. 'key1':'value1'
  27. 'key2':'value2'
  28. 'key3':'value3 value3       value3'
  29. 'user.id':'1'
  30. 'user.name':'john'
  31. 'user.surname':'doe'
  32. 'smtp_port':'25'
  33. 'smtp_password':'harDtoGueSs'
  34. 'smtp_user':'[email protected]'
  35. 'smtp_server':'smtp.example.com'
  36. Output, prefix used:
  37. 'user.id':'1'
  38. 'user.name':'john'
  39. 'user.surname':'doe'
  40. */
复制代码
Seemain.go in examples
莲紫 发表于 2016-12-16 06:38:37
围观 围观 沙发在哪里!!!
回复 支持 反对

使用道具 举报

三个地方 发表于 2016-12-30 03:40:57
收藏了,怕楼主删了!
回复 支持 反对

使用道具 举报

我要投稿

推荐阅读


回页顶回复上一篇下一篇回列表
手机版/c.CoLaBug.com ( 粤ICP备05003221号 | 粤公网安备 44010402000842号 )

© 2001-2017 Comsenz Inc.

返回顶部 返回列表