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.

73 lines
1.5 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. RequestsPerMinute int `json:"requests_per_minute"`
  16. StorageProvider StorageSettings `json:"storage_provider"`
  17. }
  18. type StorageSettings struct {
  19. Type FileSystemType `json:"type"`
  20. BasePath string `json:"base_path"`
  21. }
  22. func parseSettings(data []byte) Settings {
  23. settings := Settings{}
  24. err := json.Unmarshal(data, &settings)
  25. if err != nil {
  26. return Settings{}
  27. }
  28. return settings
  29. }
  30. func LoadSettings(fileSystem afero.Fs) (Settings, error) {
  31. workingDirectory, _ := os.Getwd()
  32. path := filepath.Join(workingDirectory, "settings.json")
  33. // Load file and parse file
  34. data, err := afero.ReadFile(fileSystem, path)
  35. if err == nil {
  36. return parseSettings(data), nil
  37. }
  38. // If file does not exist, create default settings
  39. defaultSettings := Settings{
  40. Endpoint: "127.0.0.1:8000",
  41. Token: "changeme",
  42. RequestsPerMinute: 20,
  43. StorageProvider: StorageSettings{
  44. Type: Local,
  45. BasePath: "assets",
  46. },
  47. }
  48. serializedSettings, err := json.MarshalIndent(defaultSettings, "", "\t")
  49. if err != nil {
  50. return Settings{}, err
  51. }
  52. err = afero.WriteFile(fileSystem, path, serializedSettings, os.ModePerm)
  53. if err != nil {
  54. return Settings{}, err
  55. }
  56. return defaultSettings, nil
  57. }