我使用jsonfile 來配置我的程序參數,并使用flagpackage 來配置相同的參數。當一些參數同時被json文件解析flag時,我希望使用通過flag.麻煩的是json文件路徑也是通過.解析出來的flag。調用后可以得到json路徑flag.parse(),但是參數也被解析了,那么Unmarshaljson會覆蓋flag解析的參數。示例 JSON:{ "opt1": 1, "opt2": "hello"}示例代碼:var Config = struct { Opt1 int `json:"opt1"` Opt2 string `json:"opt2"`}{ Opt1: 0, Opt2: "none",}func main() { // parse config file path var configFile string flag.StringVar(&configFile, "config", "", "config file path") // parse options flag.IntVar(&Config.Opt1, "opt1", Config.Opt1, "") flag.StringVar(&Config.Opt2, "opt2", Config.Opt2, "") // parse flags flag.Parse() // load config options from config.json file if configFile != "" { if data, err := ioutil.ReadFile(configFile); err != nil { fmt.Printf("read config file error: %v\n", err) } else if err = json.Unmarshal(data, &Config); err != nil { fmt.Printf("parse config file error: %v\n", err) } } fmt.Printf("%+v", Config)}程序示例輸出:./foo.exe -opt2 worldout:{Opt1:0 Opt2:world}./foo.exe -config config.json出去:{Opt1:1 Opt2:hello}./foo.exe -config config.json -opt2 world真正的出局:{Opt1:1 Opt2:hello}希望出局:{Opt1:1 Opt2:world}
1 回答

汪汪一只貓
TA貢獻1898條經驗 獲得超8個贊
一個簡單的解決方案是首先解析 JSON 配置文件,完成后,再繼續解析 CLI 參數。
問題在于 JSON 配置文件也是 CLI arg。
flag.Parse()最簡單的解決方案是在解析配置文件后再次調用:
// load config options from config.json file
if configFile != "" {
if data, err := ioutil.ReadFile(configFile); err != nil {
fmt.Printf("read config file error: %v\n", err)
} else if err = json.Unmarshal(data, &Config); err != nil {
fmt.Printf("parse config file error: %v\n", err)
}
// parse flags again to have precedence
flag.Parse()
}
第二個flag.Parse()將覆蓋并因此優先于來自 JSON 文件的數據。
加上這個,運行
./foo.exe -config config.json -opt2 world
輸出將是你想要的:
{Opt1:1 Opt2:world}
- 1 回答
- 0 關注
- 151 瀏覽
添加回答
舉報
0/150
提交
取消