Micro-service for file storage and processing written in Go
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

91 lines
1.9 KiB

package settings
import (
"encoding/json"
"os"
"path/filepath"
"github.com/spf13/afero"
)
const (
Local FileSystemType = iota
)
type FileSystemType int
type Settings struct {
Endpoint string `json:"endpoint"`
Authentication AuthenticationSettings `json:"authentication"`
RateLimiter RateLimiterSettings `json:"rate_limiter"`
StorageProvider StorageSettings `json:"storage_provider"`
}
type StorageSettings struct {
Type FileSystemType `json:"type"`
BasePath string `json:"base_path"`
}
type AuthenticationSettings struct {
Enabled bool `json:"enabled"`
Token string `json:"token"`
}
type RateLimiterSettings struct {
Enabled bool `json:"enabled"`
RequestsPerMinute int `json:"requests_per_minute"`
AllowedBurst int `json:"allowed_burst"`
}
func parseSettings(data []byte) Settings {
settings := Settings{}
err := json.Unmarshal(data, &settings)
if err != nil {
return Settings{}
}
return settings
}
func LoadSettings(fileSystem afero.Fs) (Settings, error) {
workingDirectory, _ := os.Getwd()
path := filepath.Join(workingDirectory, "settings.json")
// Load file and parse file
data, err := afero.ReadFile(fileSystem, path)
if err == nil {
return parseSettings(data), nil
}
// If file does not exist, create default settings
defaultSettings := Settings{
Endpoint: "127.0.0.1:8000",
Authentication: AuthenticationSettings{
Enabled: false,
Token: "changeme",
},
RateLimiter: RateLimiterSettings{
Enabled: true,
RequestsPerMinute: 20,
AllowedBurst: 5,
},
StorageProvider: StorageSettings{
Type: Local,
BasePath: "assets",
},
}
serializedSettings, err := json.MarshalIndent(defaultSettings, "", "\t")
if err != nil {
return Settings{}, err
}
err = afero.WriteFile(fileSystem, path, serializedSettings, os.ModePerm)
if err != nil {
return Settings{}, err
}
return defaultSettings, nil
}