config.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package main
  2. import (
  3. "io/ioutil"
  4. "log"
  5. "os/user"
  6. "time"
  7. "gopkg.in/yaml.v2"
  8. )
  9. var (
  10. dir, configFile string
  11. )
  12. type feed struct {
  13. URL, Template string
  14. Summary bool
  15. }
  16. type config struct {
  17. Accounts []Account
  18. LastUpdated time.Time
  19. }
  20. // An Account holds the information required to use that account.
  21. type Account struct {
  22. ClientID string
  23. ClientSecret string
  24. AccessToken string
  25. Name string
  26. InstanceURL string
  27. Feeds []feed
  28. }
  29. func readConfig() *config {
  30. usr, _ := user.Current()
  31. dir = usr.HomeDir
  32. log.Println("reading config...")
  33. configFile = "gof.yaml"
  34. config := new(config)
  35. cf, err := ioutil.ReadFile(configFile)
  36. if err != nil {
  37. log.Fatalln("Failed to read config: ", err)
  38. }
  39. err = yaml.Unmarshal(cf, &config)
  40. if err != nil {
  41. log.Panic(err)
  42. }
  43. return config
  44. }
  45. func (cf *config) updateLastUpdated() {
  46. log.Println("updating lastupdated key...")
  47. cf.LastUpdated = time.Now()
  48. }
  49. func (cf *config) Save() error {
  50. log.Println("saving config to file...")
  51. cfbytes, err := yaml.Marshal(cf)
  52. if err != nil {
  53. log.Fatalln("Failed to marshal config: ", err.Error())
  54. }
  55. err = ioutil.WriteFile(configFile, cfbytes, 0644)
  56. if err != nil {
  57. log.Fatalf("Failed to save config to file. Error: %s", err.Error())
  58. }
  59. return nil
  60. }