urbit.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package config
  2. // functions related to managing urbit config jsons & corresponding structs
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "goseg/structs"
  7. "io/ioutil"
  8. "os"
  9. "path/filepath"
  10. "sync"
  11. )
  12. var (
  13. UrbitsConfig = make(map[string]structs.UrbitDocker)
  14. urbitMutex sync.RWMutex
  15. )
  16. // retrieve struct corresponding with urbit json file
  17. func UrbitConf(pier string) structs.UrbitDocker {
  18. urbitMutex.Lock()
  19. defer urbitMutex.Unlock()
  20. return UrbitsConfig[pier]
  21. }
  22. // load urbit conf json into memory
  23. func LoadUrbitConfig(pier string) error {
  24. urbitMutex.Lock()
  25. defer urbitMutex.Unlock()
  26. // pull docker info from json
  27. confPath := filepath.Join(BasePath, "settings", "pier", pier+".json")
  28. file, err := ioutil.ReadFile(confPath)
  29. if err != nil {
  30. errmsg := fmt.Sprintf("Unable to load %s config: %v", pier, err)
  31. return fmt.Errorf(errmsg)
  32. // todo: write a new conf
  33. }
  34. // Unmarshal JSON
  35. var targetStruct structs.UrbitDocker
  36. if err := json.Unmarshal(file, &targetStruct); err != nil {
  37. errmsg := fmt.Sprintf("Error decoding %s JSON: %v", pier, err)
  38. return fmt.Errorf(errmsg)
  39. }
  40. // Store in var
  41. UrbitsConfig[pier] = targetStruct
  42. return nil
  43. }
  44. // update the in-memory struct and save it to json
  45. func UpdateUrbitConfig(inputConfig map[string]structs.UrbitDocker) error {
  46. urbitMutex.Lock()
  47. defer urbitMutex.Unlock()
  48. // update UrbitsConfig with the values from inputConfig
  49. for pier, config := range inputConfig {
  50. UrbitsConfig[pier] = config
  51. // also update the corresponding json files
  52. path := filepath.Join(BasePath, "settings", "pier", pier+".json")
  53. if err := os.MkdirAll(filepath.Dir(path), os.ModePerm); err != nil {
  54. return err
  55. }
  56. file, err := os.Create(path)
  57. if err != nil {
  58. return err
  59. }
  60. defer file.Close()
  61. encoder := json.NewEncoder(file)
  62. encoder.SetIndent("", " ")
  63. if err := encoder.Encode(&config); err != nil {
  64. return err
  65. }
  66. }
  67. return nil
  68. }