测试代码
package mainimport ("context""log""net/http""time""github.com/gin-gonic/gin""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/bson/primitive""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options"
)type Event struct {ID primitive.ObjectID `bson:"_id,omitempty" json:"id,omitempty"`Name string `bson:"name" json:"name"`Timestamp time.Time `bson:"timestamp" json:"timestamp"`
}var collection *mongo.Collectionfunc init() {clientOptions := options.Client().ApplyURI("mongodb://127.0.0.1:27017/test")client, err := mongo.Connect(context.Background(), clientOptions)if err != nil {log.Fatal(err)}err = client.Ping(context.Background(), nil)if err != nil {log.Fatal(err)}collection = client.Database("test").Collection("events")
}func createEvent(c *gin.Context) {var event Eventif err := c.ShouldBindJSON(&event); err != nil {c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})return}event.Timestamp = time.Now().Local()insertResult, err := collection.InsertOne(context.Background(), event)if err != nil {c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})return}c.JSON(http.StatusOK, insertResult)
}func getEvents(c *gin.Context) {cur, err := collection.Find(context.Background(), bson.D{})if err != nil {c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})return}defer cur.Close(context.Background())var events []Eventfor cur.Next(context.Background()) {var event Eventerr := cur.Decode(&event)if err != nil {c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})return}events = append(events, event)}if err := cur.Err(); err != nil {c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})return}c.JSON(http.StatusOK, events)
}func main() {r := gin.Default()r.POST("/events", createEvent)r.GET("/events", getEvents)r.Run(":8080")
}
测试接口
-
添加数据
-
查询数据