Using CLI args and a config file to assign values

I have a tool that I want to:

  1. look for a default config file (complete)
  2. unmarshal the data into the fields of a struct (complete)
  3. using the flag package, parse all cli args (complete)
  4. update the fields accordingly if arg != Struct.Field
  5. OR maybe I should rethink this entirely :slight_smile:

Here are some code snippets:

type Config struct {
	User    string `json:"user"`
	Port    int    `json:"port"`
	Key     string `json:"key"`
	Nodes   string `json:"nodes"`
	Syslog  bool   `json:"syslog"`
	LogPath string `json:"logpath"`
	Fatal   bool   `json:"fatal"`
}

// this is boiler plate for what I thought was best approach
func (c *Config) Rectify(uname string) {
	c.User = uname
}


func getConfig(fd string) {
	contents, e := ioutil.ReadFile(fd)
	check(e)
	e = json.Unmarshal(contents, &cfg)
	check(e)
}

func main() {
        // unmarshal; assign to cfg, hardcoded for example
	getConfig("/home/rxlx/.send_config.json")
	uname := flag.String("u", "send", "username")
        // other flags removed for brevity
	flag.Parse()
}

This is where I’m kind of stuck. I’m trying to simplify the cli usage of the tool while being more…gomatic (or is it golangish? gopherish?)

thanks

Have a look at cobra and viper

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.