How do I validate configuration on startup in Go?

In Go, validating configuration at startup is crucial for ensuring that your application runs smoothly without configuration errors. This can be achieved by several methods, such as using struct tags, custom validation functions, or libraries designed for this purpose. Below is an example of how to validate a configuration struct at startup.

package main import ( "encoding/json" "fmt" "os" "log" ) type Config struct { Port int `json:"port" validate:"required,min=8000,max=9000"` Host string `json:"host" validate:"required"` } func loadConfig(file string) (*Config, error) { config := &Config{} f, err := os.Open(file) if err != nil { return nil, err } defer f.Close() if err := json.NewDecoder(f).Decode(config); err != nil { return nil, err } return config, nil } func validateConfig(config *Config) error { if config.Port < 8000 || config.Port > 9000 { return fmt.Errorf("port must be between 8000 and 9000") } if config.Host == "" { return fmt.Errorf("host is required") } return nil } func main() { configFile := "config.json" config, err := loadConfig(configFile) if err != nil { log.Fatalf("error loading config: %s", err) } if err := validateConfig(config); err != nil { log.Fatalf("invalid config: %s", err) } fmt.Println("Configuration validated successfully!") }

Configuration validation Go startup Go config Go application startup Validate settings in Go Go config validation