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.

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