Browse Source

Add LoadSettings function error handling

feature/update-route-registration
Roman Zipp 3 years ago
committed by Fabian Vowie
parent
commit
49b17e6041
No known key found for this signature in database GPG Key ID: C27317C33B27C410
  1. 7
      main.go
  2. 20
      settings/settings.go
  3. 3
      settings/settings_test.go

7
main.go

@ -45,7 +45,10 @@ func RegisterPipelineRoutes(r *mux.Router, pipelines []pipelines.IPipeline, stor
}
func main() {
settings := settings.LoadSettings(afero.NewOsFs())
settings, err := settings.LoadSettings(afero.NewOsFs())
if err != nil {
panic(err)
}
var storageProvider storage.IStorageProvider
@ -65,7 +68,7 @@ func main() {
RegisterPipelineRoutes(r, pipes, storageProvider)
err := http.ListenAndServe(":8000", r)
err = http.ListenAndServe(settings.Endpoint, r)
if err != nil {
panic(err)
}

20
settings/settings.go

@ -28,12 +28,15 @@ type StorageSettings struct {
func parseSettings(data []byte) Settings {
settings := Settings{}
json.Unmarshal(data, &settings)
err := json.Unmarshal(data, &settings)
if err != nil {
return Settings{}
}
return settings
}
func LoadSettings(fileSystem afero.Fs) Settings {
func LoadSettings(fileSystem afero.Fs) (Settings, error) {
workingDirectory, _ := os.Getwd()
path := filepath.Join(workingDirectory, "settings.json")
@ -41,7 +44,7 @@ func LoadSettings(fileSystem afero.Fs) Settings {
data, err := afero.ReadFile(fileSystem, path)
if err == nil {
return parseSettings(data)
return parseSettings(data), nil
}
// If file does not exist, create default settings
@ -55,7 +58,14 @@ func LoadSettings(fileSystem afero.Fs) Settings {
}
serializedSettings, err := json.MarshalIndent(defaultSettings, "", "\t")
afero.WriteFile(fileSystem, path, serializedSettings, os.ModePerm)
if err != nil {
return Settings{}, err
}
err = afero.WriteFile(fileSystem, path, serializedSettings, os.ModePerm)
if err != nil {
return Settings{}, err
}
return defaultSettings
return defaultSettings, nil
}

3
settings/settings_test.go

@ -39,7 +39,8 @@ func TestSettingsLoading(t *testing.T) {
doesFileExist, _ := afero.Exists(fileSystem, path)
assert.False(t, doesFileExist)
LoadSettings(fileSystem)
_, err := LoadSettings(fileSystem)
assert.Nil(t, err)
// Settings file should be present after calling LoadSettings
doesFileExist, _ = afero.Exists(fileSystem, path)

Loading…
Cancel
Save