LoadFile loads file content with file extension and assigns to structObj
(path string, structObj interface{})
| 237 | |
| 238 | // LoadFile loads file content with file extension and assigns to structObj |
| 239 | func LoadFile(path string, structObj interface{}) (err error) { |
| 240 | log.Info().Str("path", path).Msg("load file") |
| 241 | file, err := ReadFile(path) |
| 242 | if err != nil { |
| 243 | return errors.Wrap(err, "read file failed") |
| 244 | } |
| 245 | // remove BOM at the beginning of file |
| 246 | file = bytes.TrimLeft(file, "\xef\xbb\xbf") |
| 247 | ext := filepath.Ext(path) |
| 248 | switch ext { |
| 249 | case ".json", ".har": |
| 250 | decoder := json.NewDecoder(bytes.NewReader(file)) |
| 251 | decoder.UseNumber() |
| 252 | err = decoder.Decode(structObj) |
| 253 | if err != nil { |
| 254 | err = errors.Wrap(code.LoadJSONError, err.Error()) |
| 255 | } |
| 256 | case ".yaml", ".yml": |
| 257 | err = yaml.Unmarshal(file, structObj) |
| 258 | if err != nil { |
| 259 | err = errors.Wrap(code.LoadYAMLError, err.Error()) |
| 260 | } |
| 261 | case ".env": |
| 262 | err = parseEnvContent(file, structObj) |
| 263 | if err != nil { |
| 264 | err = errors.Wrap(code.LoadEnvError, err.Error()) |
| 265 | } |
| 266 | default: |
| 267 | err = code.UnsupportedFileExtension |
| 268 | } |
| 269 | return err |
| 270 | } |
| 271 | |
| 272 | func parseEnvContent(file []byte, obj interface{}) error { |
| 273 | envMap := obj.(map[string]string) |