mirror of
https://github.com/aykhans/dodo.git
synced 2025-09-03 18:03:34 +00:00
✨ Add yaml file reader to config
This commit is contained in:
@@ -7,40 +7,54 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/aykhans/dodo/types"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
var supportedFileTypes = []string{"json", "yaml", "yml"}
|
||||
|
||||
func (config *Config) ReadFile(filePath types.ConfigFile) error {
|
||||
var (
|
||||
data []byte
|
||||
err error
|
||||
)
|
||||
|
||||
if filePath.LocationType() == types.FileLocationTypeRemoteHTTP {
|
||||
client := &http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
fileExt := filePath.Extension()
|
||||
if slices.Contains(supportedFileTypes, fileExt) {
|
||||
if filePath.LocationType() == types.FileLocationTypeRemoteHTTP {
|
||||
client := &http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
}
|
||||
|
||||
resp, err := client.Get(filePath.String())
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to fetch config file from %s", filePath)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
data, err = io.ReadAll(io.Reader(resp.Body))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read config file from %s", filePath)
|
||||
}
|
||||
} else {
|
||||
data, err = os.ReadFile(filePath.String())
|
||||
if err != nil {
|
||||
return errors.New("failed to read config file from " + filePath.String())
|
||||
}
|
||||
}
|
||||
|
||||
resp, err := client.Get(filePath.String())
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to fetch config file from %s", filePath)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
data, err = io.ReadAll(io.Reader(resp.Body))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read config file from %s", filePath)
|
||||
}
|
||||
} else {
|
||||
data, err = os.ReadFile(filePath.String())
|
||||
if err != nil {
|
||||
return errors.New("failed to read config file from " + filePath.String())
|
||||
if fileExt == "json" {
|
||||
return parseJSONConfig(data, config)
|
||||
} else if fileExt == "yml" || fileExt == "yaml" {
|
||||
return parseYAMLConfig(data, config)
|
||||
}
|
||||
}
|
||||
|
||||
return parseJSONConfig(data, config)
|
||||
return fmt.Errorf("unsupported config file type (supported types: %v)", strings.Join(supportedFileTypes, ", "))
|
||||
}
|
||||
|
||||
func parseJSONConfig(data []byte, config *Config) error {
|
||||
@@ -58,3 +72,12 @@ func parseJSONConfig(data []byte, config *Config) error {
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseYAMLConfig(data []byte, config *Config) error {
|
||||
err := yaml.Unmarshal(data, &config)
|
||||
if err != nil {
|
||||
return fmt.Errorf("YAML Config file: %s", err.Error())
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
Reference in New Issue
Block a user