db.go 901 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. package mgodb
  2. import (
  3. "context"
  4. "eta/eta_forum_admin/utils"
  5. "fmt"
  6. "go.mongodb.org/mongo-driver/mongo"
  7. "go.mongodb.org/mongo-driver/mongo/options"
  8. "go.mongodb.org/mongo-driver/mongo/readpref"
  9. "time"
  10. )
  11. var MgoClient *mongo.Client
  12. func init() {
  13. var err error
  14. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  15. defer cancel()
  16. credential := options.Credential{
  17. AuthMechanism: utils.MONGODB_CREDENTIAL,
  18. Username: "hzeta",
  19. Password: "hzeta2023",
  20. }
  21. clientOpts := options.Client().ApplyURI(utils.MONGODB_URL).SetAuth(credential)
  22. clientOpts.SetMinPoolSize(0)
  23. clientOpts.SetMaxPoolSize(100)
  24. clientOpts.SetConnectTimeout(10 * time.Second)
  25. MgoClient, err = mongo.Connect(context.TODO(), clientOpts)
  26. if err != nil {
  27. panic(err)
  28. }
  29. if err = MgoClient.Ping(ctx, readpref.Primary()); err != nil {
  30. panic(err)
  31. }
  32. fmt.Println("Connected to MongoDB!")
  33. }