1. package main
    2. import (
    3. "bytes"
    4. "encoding/json"
    5. "fmt"
    6. "log"
    7. "os"
    8. "regexp"
    9. "time"
    10. )
    11. const configFileSizeLimit = 10 << 20
    12. var defaultConfig = &struct {
    13. netTimeout int64
    14. fileDeadtime string
    15. }{
    16. netTimeout: 15,
    17. fileDeadtime: "24h",
    18. }
    19. //有了`json:network`这种注释,后面json解析就可以把相应的数据塞到对应的结构里面来
    20. type Config struct {
    21. Network NetworkConfig `json:network`
    22. Files []FileConfig `json:files`
    23. }
    24. type NetworkConfig struct {
    25. Servers []string `json:servers`
    26. SSLCertificate string `json:"ssl certificate"`
    27. SSLKey string `json:"ssl key"`
    28. SSLCA string `json:"ssl ca"`
    29. Timeout int64 `json:timeout`
    30. timeout time.Duration
    31. }
    32. type FileConfig struct {
    33. Paths []string `json:paths`
    34. Fields map[string]string `json:fields`
    35. DeadTime string `json:"dead time"`
    36. deadtime time.Duration
    37. }
    38. func main() {
    39. LoadConfig("F:/logstast_forwarder.conf")
    40. }
    41. func LoadConfig(path string) (config Config, err error) {
    42. config_file, err := os.Open(path)
    43. if err != nil {
    44. emit("Failed to open config file '%s': %s\n", path, err)
    45. return
    46. }
    47. fi, _ := config_file.Stat()
    48. if size := fi.Size(); size > (configFileSizeLimit) {
    49. emit("config file (%q) size exceeds reasonable limit (%d) - aborting", path, size)
    50. return // REVU: shouldn't this return an error, then?
    51. }
    52. if fi.Size() == 0 {
    53. emit("config file (%q) is empty, skipping", path)
    54. return
    55. }
    56. buffer := make([]byte, fi.Size())
    57. _, err = config_file.Read(buffer)
    58. emit("\n %s\n", buffer)
    59. buffer, err = StripComments(buffer) //去掉注释
    60. if err != nil {
    61. emit("Failed to strip comments from json: %s\n", err)
    62. return
    63. }
    64. buffer = []byte(os.ExpandEnv(string(buffer))) //特殊
    65. err = json.Unmarshal(buffer, &config) //解析json格式数据
    66. if err != nil {
    67. emit("Failed unmarshalling json: %s\n", err)
    68. return
    69. }
    70. fmt.Printf("111111111 %s \n", config.Network.Servers)
    71. for k, _ := range config.Files {
    72. if config.Files[k].DeadTime == "" {
    73. config.Files[k].DeadTime = defaultConfig.fileDeadtime
    74. }
    75. config.Files[k].deadtime, err = time.ParseDuration(config.Files[k].DeadTime)
    76. if err != nil {
    77. emit("Failed to parse dead time duration '%s'. Error was: %s\n", config.Files[k].DeadTime, err)
    78. return
    79. }
    80. }
    81. return
    82. }
    83. func StripComments(data []byte) ([]byte, error) {
    84. data = bytes.Replace(data, []byte("\r"), []byte(""), 0) // Windows
    85. lines := bytes.Split(data, []byte("\n")) //split to muli lines
    86. filtered := make([][]byte, 0)
    87. for _, line := range lines {
    88. match, err := regexp.Match(`^\s*#`, line)
    89. if err != nil {
    90. return nil, err
    91. }
    92. if !match {
    93. filtered = append(filtered, line)
    94. }
    95. }
    96. return bytes.Join(filtered, []byte("\n")), nil
    97. }
    98. func emit(msgfmt string, args ...interface{}) {
    99. log.Printf(msgfmt, args...)
    100. }

    Json配置文件:

    1. ## json format file
    2. {
    3. "network": {
    4. "servers": [ "localhost:5043" ]
    5. },
    6. "files": [
    7. {
    8. "paths": [""]
    9. }
    10. ]
    11. }

    输出结果:

    1. 111111111 [localhost:5043]
    2. 2015/10/05 16:45:21
    3. ## json format file
    4. {
    5. "network": {
    6. "servers": [ "localhost:5043" ]
    7. },
    8. "files": [
    9. {
    10. "paths": [""]
    11. }
    12. ]
    13. }