自从我加入Gophers团队以来已经有几周了。目前为止,一切都好。我开始了一个新项目,使用光纤Web框架来构建后端API。我使用蒙哥DB作为我的数据库。数据库/数据库package databaseimport ( "context" "log" "time" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/mongo/readpref")var DB *mongo.Database// InitMongo : Initialize mongodb...func connectToMongo() { log.Printf("Initializing database") client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017")) if err != nil { log.Fatal("Could not able to connect to the database, Reason:", err) } ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) err = client.Connect(ctx) if err != nil { log.Fatal("Context error, mongoDB:", err) } //Cancel context to avoid memory leak defer cancel() defer client.Disconnect(ctx) // Ping our db connection err = client.Ping(context.Background(), readpref.Primary()) if err != nil { log.Fatal("Ping, mongoDB:", err) } log.Printf("Database connected!") // Create a database DB = client.Database("golang-test") return}// In Golang, init() functions always initialize whenever the package is called.// So, whenever DB variable called, the init() function initializedfunc init() { connectToMongo()}控制器/mongo.controller/mongo.controller.gopackage mongocontrollerimport ( "log" "github.com/gofiber/fiber/v2" service "gitlab.com/.../services/mongoservice")// GetPersons godoc// @Summary Get persons.// @Description Get persons// @Tags persons// @Produce json// @Success 200 {object} []service.Person// @Failure 400 {object} httputil.HTTPError// @Failure 404 {object} httputil.HTTPError// @Failure 500 {object} httputil.HTTPError// @Router /v1/persons [get]func GetPersons(c *fiber.Ctx) error { res, err := service.GetPersons() if err != nil { log.Fatal("ERROR: in controller...", err) } return c.JSON(res)}以下是我存储在数据库中的数据:
1 回答
犯罪嫌疑人X
TA贡献2080条经验 获得超4个赞
您正在调用正在创建连接的同一函数 (),因此它将在调用该函数后关闭连接。您应该返回连接并在完成任务后关闭。我的意思是这些部分:defer client.Disconnect(ctx)
connectToMongo
defer cancel()
defer client.Disconnect(ctx)
- 1 回答
- 0 关注
- 31 浏览
添加回答
举报
0/150
提交
取消