How to parse flags from a configuration file and override them with command-line flags in Go?

To parse flags from a configuration file and override them with command-line flags in Go, you can use the flag package along with a configuration package, such as viper. Here's a step-by-step guide to achieve this:

Step 1: Install the required packages

go get -u github.com/spf13/viper

Step 2: Create a configuration file Assume you have a configuration file named config.yaml with some initial values:

database: host: localhost port: 5432 username: root password: password123

Step 3: Import the necessary packages

import ( "flag" "fmt" "log" "github.com/spf13/viper" )

Step 4: Define a struct to hold the configuration values

type Config struct { Database struct { Host string Port int Username string Password string } }

Step 5: Load and parse the configuration file

func loadConfig() (*Config, error) { var cfg Config viper.SetConfigName("config") viper.SetConfigType("yaml") viper.AddConfigPath(".") err := viper.ReadInConfig() if err != nil { return nil, fmt.Errorf("failed to read config file: %w", err) } err = viper.Unmarshal(&cfg) if err != nil { return nil, fmt.Errorf("failed to unmarshal config file: %w", err) } return &cfg, nil }

Step 6: Define and parse command-line flags

func parseFlags(cfg *Config) { flag.StringVar(&cfg.Database.Host, "db_host", cfg.Database.Host, "Database host") flag.IntVar(&cfg.Database.Port, "db_port", cfg.Database.Port, "Database port") flag.StringVar(&cfg.Database.Username, "db_user", cfg.Database.Username, "Database username") flag.StringVar(&cfg.Database.Password, "db_pass", cfg.Database.Password, "Database password") flag.Parse() }

Step 7: Implement main function

func main() { cfg, err := loadConfig() if err != nil { log.Fatal(err) } parseFlags(cfg) // Use the configuration values fmt.Println("Database Host:", cfg.Database.Host) fmt.Println("Database Port:", cfg.Database.Port) fmt.Println("Database Username:", cfg.Database.Username) fmt.Println("Database Password:", cfg.Database.Password) }

Now you can run your program and provide command-line flags to override the values from the configuration file:

go run main.go --db_host=localhost --db_port=5433 --db_user=admin --db_pass=admin123

The command-line flags will override the corresponding values from the configuration file when provided.