自從我加入Gophers團(tuán)隊以來已經(jīng)有幾周了。目前為止,一切都好。我開始了一個新項目,使用光纖Web框架來構(gòu)建后端API。我使用蒙哥DB作為我的數(shù)據(jù)庫。數(shù)據(jù)庫/數(shù)據(jù)庫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)}以下是我存儲在數(shù)據(jù)庫中的數(shù)據(jù):
1 回答

犯罪嫌疑人X
TA貢獻(xiàn)2080條經(jīng)驗 獲得超4個贊
您正在調(diào)用正在創(chuàng)建連接的同一函數(shù) (),因此它將在調(diào)用該函數(shù)后關(guān)閉連接。您應(yīng)該返回連接并在完成任務(wù)后關(guān)閉。我的意思是這些部分:defer client.Disconnect(ctx)
connectToMongo
defer cancel()
defer client.Disconnect(ctx)
- 1 回答
- 0 關(guān)注
- 40 瀏覽
添加回答
舉報
0/150
提交
取消