Go语言+Vue3零基础入门全栈班09 Go语言+MongoDB开发用户管理系统API实战_20240730 课程笔记
package main
import (
"context"
"fmt"
"log"
"net/http"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var collection *mongo.Collection
func main() {
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
err = client.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("Connected to MongoDB!")
collection = client.Database("gostack_users").Collection("users")
http.HandleFunc("/users", getUsers)
http.ListenAndServe(":27018", nil)
}
func getUsers(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
var results []bson.M
cursor, err := collection.Find(ctx, bson.D{})
if err != nil {
log.Fatal(err)
}
defer cursor.Close(ctx)
for cursor.Next(ctx) {
var result bson.M
err := cursor.Decode(&result)
if err != nil {
log.Fatal(err)
}
results = append(results, result)
}
if err := cursor.Err(); err != nil {
log.Fatal(err)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, results)
}
这段代码首先建立了与MongoDB的连接,然后定义了一个getUsers
函数,这个函数会处理对/users
路径的HTTP GET请求。它会从MongoDB的users
集合中检索所有用户,并以JSON格式返回。这个例子展示了如何使用Go语言和MongoDB的官方驱动程序进行数据库操作。
评论已关闭