GraphQL API and utilities for the rpdata project
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.

102 lines
2.3 KiB

  1. package config
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "log"
  6. "os"
  7. "strings"
  8. "sync"
  9. "gopkg.in/yaml.v2"
  10. )
  11. var globalMutex sync.Mutex
  12. var global *Config
  13. // Config is configuration data
  14. type Config struct {
  15. Space Space `json:"space" yaml:"space"`
  16. Database Database `json:"database" yaml:"database"`
  17. Wiki Wiki `json:"wiki" yaml:"wiki"`
  18. }
  19. // Space is configuration for spaces.
  20. type Space struct {
  21. Enabled bool `json:"enabled" yaml:"enabled"`
  22. Host string `json:"host" yaml:"host"`
  23. AccessKey string `json:"accessKey" yaml:"accessKey"`
  24. SecretKey string `json:"secretKey" yaml:"secretKey"`
  25. Bucket string `json:"bucket" yaml:"bucket"`
  26. MaxSize int64 `json:"maxSize" yaml:"maxSize"`
  27. Root string `json:"root" yaml:"root"`
  28. }
  29. // Database is configuration for spaces.
  30. type Database struct {
  31. Driver string `json:"driver" yaml:"driver"`
  32. Host string `json:"host" yaml:"host"`
  33. Port int `json:"port" yaml:"port"`
  34. Db string `json:"db" yaml:"db"`
  35. Username string `json:"username" yaml:"username"`
  36. Password string `json:"password" yaml:"password"`
  37. Mechanism string `json:"mechanism" yaml:"mechanism"`
  38. }
  39. // Wiki is the wiki stuff.
  40. type Wiki struct {
  41. URL string `json:"url" yaml:"url"`
  42. }
  43. // Load loads config stuff
  44. func (config *Config) Load(filename string) error {
  45. log.Println("Trying to load config from " + filename)
  46. stat, err := os.Stat(filename)
  47. if err != nil {
  48. return err
  49. }
  50. if stat.Size() < 1 {
  51. return errors.New("File is empty")
  52. }
  53. file, err := os.Open(filename)
  54. if err != nil {
  55. return err
  56. }
  57. if strings.HasSuffix(filename, ".json") {
  58. return json.NewDecoder(file).Decode(config)
  59. }
  60. return yaml.NewDecoder(file).Decode(config)
  61. }
  62. // LoadAny loads the first of these files it can find
  63. func (config *Config) LoadAny(filenames ...string) error {
  64. for _, filename := range filenames {
  65. if err := config.Load(filename); err != nil {
  66. continue
  67. }
  68. return nil
  69. }
  70. return errors.New("Failed to load configuration files")
  71. }
  72. // Global gets the global configuration, loading it if this is the first caller
  73. func Global() Config {
  74. globalMutex.Lock()
  75. if global == nil {
  76. global = &Config{}
  77. err := global.LoadAny("/etc/aiterp/rpdata.yaml", "/etc/aiterp/rpdata.json", "./config.yaml", "./config.json")
  78. if err != nil {
  79. log.Fatalln(err)
  80. }
  81. }
  82. globalMutex.Unlock()
  83. return *global
  84. }