Documentation
README
Go Idioms
Error Handling
// Return errors, never panic in library code
func LoadConfig(path string) (Config, error) {
data, err := os.ReadFile(path)
if err != nil {
return Config{}, fmt.Errorf("reading config %s: %w", path, err)
}
var cfg Config
if err := json.Unmarshal(data, &cfg); err != nil {
return Config{}, fmt.Errorf("parsing config: %w", err)
}
return cfg, nil
}
Rules:
- Always wrap errors with context using
fmt.Errorf("context: %w", err) - Use
%wto allow callers to useerrors.Isanderrors.As - Handle errors at the appropriate level; do not log and return the same error
- Define sentinel errors for expected conditions
This is the opening of the README. Read the full README on GitHub.