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!")
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?