package main import ( "context" "fmt" "log" "math/rand" "time" "github.com/bxcodec/faker/v3" "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/cors" "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 Atest struct { Id primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"` Title string `json:"title,omitempty" bson:"title,omitempty"` Description string `json:"description,omitempty" bson:"description,omitempty"` Value int `json:"value,omitempty" bson:"value,omitempty"` } func main() { ctx, _ := context.WithTimeout(context.Background(), 10*time.Second) client, _ := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017")) db := client.Database("go_test") app := fiber.New() app.Use(cors.New()) app.Post("/api/atest", func(c *fiber.Ctx) error { collection := db.Collection("atest") ctx, _ := context.WithTimeout(context.Background(), 10*time.Second) atest_item := Atest{ Title: faker.Word(), Description: faker.Paragraph(), Value: rand.Intn(90) + 10, } r, err := collection.InsertOne(ctx, atest_item) if err != nil { return (err) } return c.JSON(fiber.Map{ "message": fmt.Sprintf("insert success: %s", r.InsertedID), }) }) app.Get("/api/atest", func(c *fiber.Ctx) error { collection := db.Collection("atest") ctx, _ := context.WithTimeout(context.Background(), 10*time.Second) var testitems []Atest cursor, _ := collection.Find(ctx, bson.M{}) defer cursor.Close(ctx) for cursor.Next(ctx) { var atestitem Atest cursor.Decode(&atestitem) testitems = append(testitems, atestitem) } return c.JSON(testitems) }) app.Static("/", "dist") app.Get("/*", func(ctx *fiber.Ctx) error { return ctx.SendFile("./dist/index.html") }) // app.Get("/", func(c *fiber.Ctx) error { // return c.SendFile("