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.

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