自從我加入Gophers團(tuán)隊(duì)以來已經(jīng)有幾周了。目前為止,一切都好。我開始了一個(gè)新項(xiàng)目,使用光纖Web框架來構(gòu)建后端API。我使用蒙哥DB作為我的數(shù)據(jù)庫(kù)。數(shù)據(jù)庫(kù)/數(shù)據(jù)庫(kù)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)}以下是我存儲(chǔ)在數(shù)據(jù)庫(kù)中的數(shù)據(jù):
轉(zhuǎn)到:客戶端已斷開連接
動(dòng)漫人物
2022-09-19 21:19:37