main2.go 1.92 KB
package main

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
	"time"
)

var (
	client     *mongo.Client
	err        error
	result     *mongo.InsertOneResult
	collection *mongo.Collection
)

// @APIVersion 1.0.0
// @APITitle 乐游图后端接口文档
// @BasePath 正式 leyoutu.st-i.com.cn; 测试 letu.api.imagchina.com
func main() {

	// Set client options
	clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
	clientOptions.SetLocalThreshold(3 * time.Second)  //只使用与mongo操作耗时小于3秒的
	clientOptions.SetMaxConnIdleTime(5 * time.Second) //指定连接可以保持空闲的最大毫秒数
	clientOptions.SetMaxPoolSize(4096)                //使用最大的连接数

	// Connect to MongoDB
	client, err = mongo.Connect(context.TODO(), clientOptions)

	if err != nil {
		log.Fatal(err)
	}

	// Check the connection
	err = client.Ping(context.TODO(), nil)

	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Connected to MongoDB!")

	collection = client.Database("LeYouTu").Collection("LogRecord")

	r := gin.Default()
	r.GET("/AllScenic", func(c *gin.Context) {
		c.Header("Access-Control-Allow-Origin", c.Request.Header.Get("Origin"))
		c.Header("Access-Control-Allow-Credentials", "true")

		//var aItems = DB.SItem{}
		//if err = collection.FindOne(context.TODO(), bson.D{{}}).Decode(&aItems); err != nil {
		//	println(err)
		//}

		record := &LogRecord{
			JobName: "job10",
			Command: "echo hello",
			Err:     "",
			Content: "hello",
		}

		if result, err = collection.InsertOne(context.TODO(), record); err != nil {
			fmt.Println(err)
			return
		}

		c.JSON(200, "ok")

	})

	r.Run(":8080")
}

type LogRecord struct {
	JobName string `bson:"jobName"` // 任务名
	Command string `bson:"command"` // shell命令
	Err     string `bson:"err"`     // 脚本错误
	Content string `bson:"content"` // 脚本输出
}