在命令之间共享信息
就像评论中所说的那样,如果您需要跨命令共享数据,则需要将其持久化。您使用的结构无关紧要,但是为了简单起见,由于JSON是当前用于数据交换的最扩展的语言,我们将使用它。
我应该在哪里创建它(路径)?
我的建议是使用用户的住所。许多应用程序在此处保存其配置。这样可以轻松实现多环境解决方案。假设您的配置文件将命名为 myApp 。
func configPath() string { cfgFile := ".myApp" usr, _ := user.Current() return path.Join(usr.HomeDir, cfgFile)}什么时候清洗?
那显然取决于您的要求。但是,如果你经常需要运行
pre,并
run按照这个顺序,我敢打赌,你可以以后inmediately清理
run执行,当它不会再需要。
如何存放呢?
这很简单。如果您需要保存的是您的
config结构,则可以执行以下操作:
func saveConfig(c config) { jsonC, _ := json.Marshal(c) ioutil.WriteFile(configPath(), jsonC, os.ModeAppend)}并阅读吗?
func readConfig() config { data, _ := ioutil.ReadFile(configPath()) var cfg config json.Unmarshal(data, &cfg) return cfg}流
// pre command// persist to file the data you needsaveConfig(config{ id: "id", path: "path", wd: "wd",})// run command// retrieve the previously stored informationcfg := readConfig()// from now you can use the data generated by `pre`免责声明 :我已简短删除了所有错误处理。



