config.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "os"
  6. "time"
  7. "gopkg.in/yaml.v2"
  8. )
  9. var (
  10. Version string
  11. Buildtime string
  12. configFile string
  13. )
  14. type feed struct {
  15. URL, Template string
  16. Format string
  17. Visibility string
  18. Sensitive bool
  19. ContentWarning string
  20. }
  21. type config struct {
  22. Accounts []account
  23. LastUpdated time.Time
  24. HttpConfig httpConfig
  25. Meta meta
  26. }
  27. type meta struct {
  28. Name string
  29. Version string
  30. Buildtime string
  31. }
  32. type account struct {
  33. AccessToken string
  34. Name string
  35. InstanceURL string
  36. Feeds []feed
  37. }
  38. type httpConfig struct {
  39. UserAgent string
  40. }
  41. func readConfig(fileName string) *config {
  42. log.Println("reading config...")
  43. configFile = fileName
  44. config := new(config)
  45. cf, err := os.ReadFile(configFile)
  46. if err != nil {
  47. log.Fatalln("Failed to read config: ", err)
  48. }
  49. err = yaml.Unmarshal(cf, &config)
  50. if err != nil {
  51. log.Panic(err)
  52. }
  53. if debug {
  54. log.Printf("Config:\n\n%v", config)
  55. }
  56. config.Meta.Name = "gof"
  57. config.Meta.Version = Version
  58. config.Meta.Buildtime = Buildtime
  59. config.HttpConfig.UserAgent = fmt.Sprintf("%s/%s",
  60. config.Meta.Name, config.Meta.Version)
  61. return config
  62. }
  63. func (cf *config) updateLastUpdated() {
  64. log.Println("updating LastUpdated key...")
  65. cf.LastUpdated = time.Now()
  66. }
  67. func (cf *config) Save() error {
  68. log.Println("saving config to file...")
  69. cfBytes, err := yaml.Marshal(cf)
  70. if err != nil {
  71. return err
  72. }
  73. err = os.WriteFile(configFile, cfBytes, 0644)
  74. if err != nil {
  75. return err
  76. }
  77. return nil
  78. }