BindFile binds a filename (fullpath) to "c" Configuration. The file format is either JSON or YAML and it should be suffixed with .json or .yml/.yaml.
(filename string)
| 142 | // The file format is either JSON or YAML and it should be suffixed |
| 143 | // with .json or .yml/.yaml. |
| 144 | func (c *Configuration) BindFile(filename string) error { |
| 145 | switch filepath.Ext(filename) { |
| 146 | case ".json": |
| 147 | contents, err := os.ReadFile(filename) |
| 148 | if err != nil { |
| 149 | if errors.Is(err, os.ErrNotExist) { |
| 150 | generatedConfig := MustGenerateConfiguration() |
| 151 | if generatedYAML, gErr := generatedConfig.ToJSON(); gErr == nil { |
| 152 | err = fmt.Errorf("%w: example:\n\n%s", err, generatedYAML) |
| 153 | } |
| 154 | } |
| 155 | return err |
| 156 | } |
| 157 | |
| 158 | return json.Unmarshal(contents, c) |
| 159 | default: |
| 160 | contents, err := os.ReadFile(filename) |
| 161 | if err != nil { |
| 162 | if errors.Is(err, os.ErrNotExist) { |
| 163 | generatedConfig := MustGenerateConfiguration() |
| 164 | if generatedYAML, gErr := generatedConfig.ToYAML(); gErr == nil { |
| 165 | err = fmt.Errorf("%w: example:\n\n%s", err, generatedYAML) |
| 166 | } |
| 167 | } |
| 168 | return err |
| 169 | } |
| 170 | |
| 171 | return yaml.Unmarshal(contents, c) |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | // ToYAML returns the "c" Configuration's contents as raw yaml byte slice. |
| 176 | func (c *Configuration) ToYAML() ([]byte, error) { |