Skip to content

Conversation

@vinicius73
Copy link

This PR adds a new FileReader option that allows users to preprocess configuration files before they are parsed by fig's decoders. This enables use cases like environment variable substitution, template processing, and custom file formats.

Use Cases

  1. Environment Variable Substitution: Preprocess config files to expand environment variables
  2. Template Processing: Apply custom transformations before parsing
  3. Custom File Formats: Support encrypted or compressed configuration files
  4. Dynamic Configuration: Modify configuration content based on runtime conditions

Example Usage

// Custom file reader that expands environment variables
fileReader := func(filePath string) (io.Reader, error) {
    file, err := os.Open(filePath)
    if err != nil {
        return nil, err
    }
    defer file.Close()
    
    content, err := io.ReadAll(file)
    if err != nil {
        return nil, err
    }
    
    // Expand environment variables in the content
    expanded := os.ExpandEnv(string(content))
    return strings.NewReader(expanded), nil
}

var cfg Config
err := fig.Load(&cfg, fig.WithFileReader(fileReader))

- Add FileReader type to enable custom file preprocessing before parsing
- Implement WithFileReader option to configure custom file readers
- Replace direct os.Open calls with configurable fileReader function
- Add type assertion for io.Closer to handle cleanup automatically
- Add defaultFileReader function maintaining backward compatibility
- Add comprehensive tests for FileReader functionality with preprocessing scenarios
- Update documentation with FileReader section and os.ExpandEnv example
- Support use cases like environment variable substitution and template processing
@vinicius73 vinicius73 force-pushed the feature/pre-process-file-content branch from 4cdf733 to ae0c71c Compare October 15, 2025 15:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant