72 lines
2.1 KiB
Go
72 lines
2.1 KiB
Go
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.Get("/", func(c *fiber.Ctx) error {
|
|
|
|
return c.SendString("<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>Mongo Test</title></head><body><h1>Hello, World 👋!\n</h1><p><a href=\"/atest\">atest records</a></p></body></html>")
|
|
})
|
|
|
|
log.Fatal(app.Listen(":3000"))
|
|
}
|