Added http support to 'JSONConfigReader' function

This commit is contained in:
2025-03-09 05:00:33 +04:00
parent f721abb583
commit cc2a6eb367
2 changed files with 36 additions and 9 deletions

View File

@@ -2,17 +2,46 @@ package readers
import (
"encoding/json"
"fmt"
"net/http"
"os"
"strings"
"time"
"io"
"github.com/aykhans/dodo/config"
customerrors "github.com/aykhans/dodo/custom_errors"
)
func JSONConfigReader(filePath string) (*config.JSONConfig, error) {
data, err := os.ReadFile(filePath)
if err != nil {
return nil, customerrors.OSErrorFormater(err)
var (
data []byte
err error
)
if strings.HasPrefix(filePath, "http://") || strings.HasPrefix(filePath, "https://") {
client := &http.Client{
Timeout: 10 * time.Second,
}
resp, err := client.Get(filePath)
if err != nil {
return nil, fmt.Errorf("failed to fetch JSON config from %s", filePath)
}
defer resp.Body.Close()
data, err = io.ReadAll(io.Reader(resp.Body))
if err != nil {
return nil, fmt.Errorf("failed to read JSON config from %s", filePath)
}
} else {
data, err = os.ReadFile(filePath)
if err != nil {
return nil, customerrors.OSErrorFormater(err)
}
}
jsonConf := config.NewJSONConfig(
config.NewConfig("", 0, 0, 0, nil),
nil, nil, nil, nil, nil,
@@ -32,5 +61,6 @@ func JSONConfigReader(filePath string) (*config.JSONConfig, error) {
}
return nil, customerrors.NewInvalidFileError(filePath, err)
}
return jsonConf, nil
}