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.

71 lines
1.4 KiB

  1. package settings
  2. import (
  3. "encoding/json"
  4. "os"
  5. "path/filepath"
  6. "github.com/spf13/afero"
  7. )
  8. const (
  9. Local FileSystemType = iota
  10. )
  11. type FileSystemType int
  12. type Settings struct {
  13. Endpoint string `json:"endpoint"`
  14. Token string `json:"token"`
  15. StorageProvider StorageSettings `json:"storage_provider"`
  16. }
  17. type StorageSettings struct {
  18. Type FileSystemType `json:"type"`
  19. BasePath string `json:"base_path"`
  20. }
  21. func parseSettings(data []byte) Settings {
  22. settings := Settings{}
  23. err := json.Unmarshal(data, &settings)
  24. if err != nil {
  25. return Settings{}
  26. }
  27. return settings
  28. }
  29. func LoadSettings(fileSystem afero.Fs) (Settings, error) {
  30. workingDirectory, _ := os.Getwd()
  31. path := filepath.Join(workingDirectory, "settings.json")
  32. // Load file and parse file
  33. data, err := afero.ReadFile(fileSystem, path)
  34. if err == nil {
  35. return parseSettings(data), nil
  36. }
  37. // If file does not exist, create default settings
  38. defaultSettings := Settings{
  39. Endpoint: "127.0.0.1:8000",
  40. Token: "changeme",
  41. StorageProvider: StorageSettings{
  42. Type: Local,
  43. BasePath: "assets",
  44. },
  45. }
  46. serializedSettings, err := json.MarshalIndent(defaultSettings, "", "\t")
  47. if err != nil {
  48. return Settings{}, err
  49. }
  50. err = afero.WriteFile(fileSystem, path, serializedSettings, os.ModePerm)
  51. if err != nil {
  52. return Settings{}, err
  53. }
  54. return defaultSettings, nil
  55. }