FIX: find config format from content : seek start of file before each

This commit is contained in:
Adrien Marquès 2018-11-15 14:48:02 +01:00
parent 8c3b300ab5
commit b26dec8576
2 changed files with 15 additions and 13 deletions

View File

@ -3,7 +3,6 @@ package cnf
import (
"errors"
"fmt"
"io"
"os"
"path/filepath"
)
@ -50,15 +49,11 @@ func Load(path string) (ConfigurationFormat, error) {
}
// 3. open file
file, err := os.Open(path)
// 4. Try to guess from the content
confFormat, err := loadFromContent(path)
if err != nil {
return nil, err
}
defer file.Close()
// 4. Try to guess from the content
confFormat = loadFromContent(file)
if confFormat == nil {
return nil, ErrUnknownFormat
}
@ -84,13 +79,21 @@ func loadFromExtension(ext string) ConfigurationFormat {
}
func loadFromContent(file io.Reader) ConfigurationFormat {
func loadFromContent(path string) (ConfigurationFormat, error) {
// extensions ordered by unicity of the language's syntax
extensions := []string{".json", ".yaml", ".nginx", ".ini"}
// 3. open file
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
// extensions ordered by strictness of the language's syntax
extensions := []string{".json", ".nginx", ".yaml", ".ini"}
// try to load each available extension
for _, ext := range extensions {
file.Seek(0, 0)
// load parser
c := loadFromExtension(ext)
@ -101,10 +104,10 @@ func loadFromContent(file io.Reader) ConfigurationFormat {
// parse
_, err := c.ReadFrom(file)
if err == nil {
return c
return c, nil
}
}
return nil
return nil, ErrUnknownFormat
}

View File

@ -153,5 +153,4 @@ func (d *Decoder) Decode(v interface{}) error {
}
return nil
}