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.

103 lines
2.4 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. URLRoot string `json:"urlRoot" yaml:"urlRoot"`
  29. }
  30. // Database is configuration for spaces.
  31. type Database struct {
  32. Driver string `json:"driver" yaml:"driver"`
  33. Host string `json:"host" yaml:"host"`
  34. Port int `json:"port" yaml:"port"`
  35. Db string `json:"db" yaml:"db"`
  36. Username string `json:"username" yaml:"username"`
  37. Password string `json:"password" yaml:"password"`
  38. Mechanism string `json:"mechanism" yaml:"mechanism"`
  39. }
  40. // Wiki is the wiki stuff.
  41. type Wiki struct {
  42. URL string `json:"url" yaml:"url"`
  43. }
  44. // Load loads config stuff
  45. func (config *Config) Load(filename string) error {
  46. log.Println("Trying to load config from " + filename)
  47. stat, err := os.Stat(filename)
  48. if err != nil {
  49. return err
  50. }
  51. if stat.Size() < 1 {
  52. return errors.New("File is empty")
  53. }
  54. file, err := os.Open(filename)
  55. if err != nil {
  56. return err
  57. }
  58. if strings.HasSuffix(filename, ".json") {
  59. return json.NewDecoder(file).Decode(config)
  60. }
  61. return yaml.NewDecoder(file).Decode(config)
  62. }
  63. // LoadAny loads the first of these files it can find
  64. func (config *Config) LoadAny(filenames ...string) error {
  65. for _, filename := range filenames {
  66. if err := config.Load(filename); err != nil {
  67. continue
  68. }
  69. return nil
  70. }
  71. return errors.New("Failed to load configuration files")
  72. }
  73. // Global gets the global configuration, loading it if this is the first caller
  74. func Global() Config {
  75. globalMutex.Lock()
  76. if global == nil {
  77. global = &Config{}
  78. err := global.LoadAny("/etc/aiterp/rpdata.yaml", "/etc/aiterp/rpdata.json", "./config.yaml", "./config.json")
  79. if err != nil {
  80. log.Fatalln(err)
  81. }
  82. }
  83. globalMutex.Unlock()
  84. return *global
  85. }