mirror of
https://github.com/aykhans/dodo.git
synced 2025-04-25 04:33:08 +00:00
- Moved readers to the config package - Added an option to read remote config files - Moved the validation package to the config package and removed the validator dependency - Moved the customerrors package to the config package - Replaced fatih/color with jedib0t/go-pretty/v6/text - Removed proxy check functionality - Added param, header, cookie, body, and proxy flags to the CLI - Allowed multiple values for the same key in params, headers, and cookies
61 lines
1.4 KiB
Go
61 lines
1.4 KiB
Go
package config
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
"time"
|
|
|
|
"github.com/aykhans/dodo/types"
|
|
)
|
|
|
|
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,
|
|
}
|
|
|
|
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())
|
|
}
|
|
}
|
|
|
|
return parseJSONConfig(data, config)
|
|
}
|
|
|
|
func parseJSONConfig(data []byte, config *Config) error {
|
|
err := json.Unmarshal(data, &config)
|
|
if err != nil {
|
|
switch parsedErr := err.(type) {
|
|
case *json.SyntaxError:
|
|
return fmt.Errorf("JSON Config file: invalid syntax at byte offset %d", parsedErr.Offset)
|
|
case *json.UnmarshalTypeError:
|
|
return fmt.Errorf("JSON Config file: invalid type %v for field %s, expected %v", parsedErr.Value, parsedErr.Field, parsedErr.Type)
|
|
default:
|
|
return fmt.Errorf("JSON Config file: %s", err.Error())
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|