main.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package main
  2. import (
  3. "box-cost/el"
  4. "box-cost/model"
  5. "context"
  6. "fmt"
  7. "log"
  8. "os"
  9. "time"
  10. "github.com/spf13/viper"
  11. "go.mongodb.org/mongo-driver/bson"
  12. "go.mongodb.org/mongo-driver/bson/primitive"
  13. "go.mongodb.org/mongo-driver/mongo"
  14. "go.mongodb.org/mongo-driver/mongo/options"
  15. )
  16. const (
  17. MONGODB_URI = "mongodb://root:boxcost@124.71.139.24:37030/box-cost?authSource=admin"
  18. CONFIG_FILE = "app.yaml"
  19. )
  20. type AppConf struct {
  21. Plans []string `yaml:"plans"`
  22. }
  23. func LoadConfFile() (*AppConf, error) {
  24. file, err := os.Open(CONFIG_FILE)
  25. if err != nil {
  26. fmt.Println("open file err:", err)
  27. return nil, err
  28. }
  29. v := viper.New()
  30. v.SetConfigType("yaml")
  31. err = v.ReadConfig(file)
  32. if err != nil {
  33. return nil, err
  34. }
  35. c := new(AppConf)
  36. err = v.Unmarshal(c)
  37. return c, err
  38. }
  39. func main() {
  40. // 读取配置
  41. conf, err := LoadConfFile()
  42. if err != nil {
  43. log.Fatal(err)
  44. }
  45. planIds := conf.Plans
  46. // 连接数据库
  47. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  48. client, err := mongo.Connect(ctx, options.Client().ApplyURI(MONGODB_URI))
  49. if err != nil {
  50. log.Fatal(err)
  51. }
  52. defer cancel()
  53. if err != nil {
  54. log.Fatal(err)
  55. }
  56. defer client.Disconnect(ctx)
  57. collection := client.Database("box-cost").Collection("product-plan")
  58. plans := []*model.ProductPlan{}
  59. for _, planIdstr := range planIds {
  60. planId, _ := primitive.ObjectIDFromHex(planIdstr)
  61. fmt.Println(planIdstr)
  62. plan := &model.ProductPlan{}
  63. err := collection.FindOne(context.Background(), bson.M{"_id": planId}).Decode(plan)
  64. if err != nil {
  65. log.Fatal(err)
  66. }
  67. plans = append(plans, plan)
  68. }
  69. fmt.Println("更新中,请稍等...")
  70. // 更新excel
  71. el.UpdateExcel(client, plans)
  72. }