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 ( import (
"errors" "errors"
"fmt" "fmt"
"io"
"os" "os"
"path/filepath" "path/filepath"
) )
@ -50,15 +49,11 @@ func Load(path string) (ConfigurationFormat, error) {
} }
// 3. open file // 4. Try to guess from the content
file, err := os.Open(path) confFormat, err := loadFromContent(path)
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer file.Close()
// 4. Try to guess from the content
confFormat = loadFromContent(file)
if confFormat == nil { if confFormat == nil {
return nil, ErrUnknownFormat 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 // 3. open file
extensions := []string{".json", ".yaml", ".nginx", ".ini"} 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 // try to load each available extension
for _, ext := range extensions { for _, ext := range extensions {
file.Seek(0, 0)
// load parser // load parser
c := loadFromExtension(ext) c := loadFromExtension(ext)
@ -101,10 +104,10 @@ func loadFromContent(file io.Reader) ConfigurationFormat {
// parse // parse
_, err := c.ReadFrom(file) _, err := c.ReadFrom(file)
if err == nil { 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 return nil
} }