新建json文件
首先新建一个config.json文件,内容如下:
1 2 3 4 5 6 7 8 9 10 11 | { "email":{ "username":"username", "password":"password", "port":25 }, "connecton":{ "username":"username", "password":"password" } } |
生成与之匹配的struct
1 2 3 4 5 6 7 8 9 10 11 | type Config struct { Email struct { Username string `json:"username"` Password string `json:"password"` Port int `json:"port"` } `json:"email"` Connecton struct { Username string `json:"username"` Password string `json:"password"` } `json:"connecton"` } |
读取文件并解析
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | func ParseConfig() Config { var config Config currentDir, err := filepath.Abs(filepath.Dir(os.Args[0])) if err != nil { fmt.Printf("get current directory err: %v\n", err) } jsontext, err := ioutil.ReadFile(currentDir + "\\" + configName) if err != nil { fmt.Printf("read config.json file err: %v\n", err) } err = json.Unmarshal(jsontext, &config) if err != nil { fmt.Printf("paser config.json err: %v\n", err) } fmt.Printf("parse config.json sucessfully.\n") return config } |