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.

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