main.go 8.9 KB
package main

import (
	"encoding/json"
	"flag"
	"github.com/aarongao/tools"
	"github.com/davecgh/go-spew/spew"
	"github.com/gin-gonic/gin"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"letu/Api"
	"letu/Config"
	"letu/DB"
	"letu/Lib/Auth"
	"letu/Lib/Cache"
	"letu/Lib/DelayMessage"
	"log"
	"os"
	"time"
)

// @APIVersion 1.0.0
// @APITitle 乐游图后端接口文档
// @BasePath 正式 leyoutu.st-i.com.cn; 测试 leyoutu.sti-uat.com
var Gin *gin.Engine

func main() {

	// 读取配置文件
	dir, _ := os.Getwd()
	file, _ := os.Open(dir + "/Config/config.json")
	defer file.Close()
	decoder := json.NewDecoder(file)
	err := decoder.Decode(&Config.Info)
	tools.CheckError(err)

	// 启动参数中的端口号
	var runPort string
	flag.StringVar(&runPort, "port", "", "端口号,默认为8080")
	flag.Parse()


	// 连接数据库
	// Set client options
	clientOptions := options.Client()
	if Config.Info.Env == "DEV" {
		clientOptions.ApplyURI("mongodb://" + Config.Info.DbPath)
	} else if Config.Info.Env == "PRODUCT" {
		credential := options.Credential{
			AuthMechanism: "SCRAM-SHA-1",
			AuthSource:    Config.Info.DbName,
			Username:      Config.Info.DbUser,
			Password:      Config.Info.DbPassword,
		}
		clientOptions.ApplyURI("mongodb://" + Config.Info.DbPath).SetAuth(credential)
	} else {
		log.Fatal("未知的运行环境 DEV or PRODUCT")
		return
	}

	clientOptions.SetLocalThreshold(3 * time.Second)  //只使用与mongo操作耗时小于3秒的
	clientOptions.SetMaxConnIdleTime(5 * time.Second) //指定连接可以保持空闲的最大毫秒数
	clientOptions.SetMaxPoolSize(4096)                //使用最大的连接数

	// Connect to MongoDB
	client, err := mongo.Connect(tools.GetContext(), clientOptions)
	if err != nil {
		log.Fatal(err)
	}

	// Check the connection
	err = client.Ping(tools.GetContext(), nil)
	if err != nil {
		log.Fatal(err)
	}
	log.Println("Connected to MongoDB!")

	//获取文档集
	DB.DB = client.Database(Config.Info.DbName)

	DB.CItem = DB.DB.Collection("Item")
	DB.CComplaint = DB.DB.Collection("Complaint")
	DB.CInvestigation = DB.DB.Collection("Investigation")
	DB.CMember = DB.DB.Collection("Member")
	DB.CCommodity = DB.DB.Collection("Commodity")
	DB.CTags = DB.DB.Collection("Tags")
	DB.CScenic = DB.DB.Collection("Scenic")
	DB.CLine = DB.DB.Collection("Line")
	DB.CUserLog = DB.DB.Collection("UserLog")
	DB.CSystemLog = DB.DB.Collection("SystemLog")
	DB.CInvestigation = DB.DB.Collection("Investigation")
	DB.CTrajectory = DB.DB.Collection("Trajectory")
	DB.CIcons = DB.DB.Collection("Icons")
	DB.CDevice = DB.DB.Collection("Device")
	DB.CNotice = DB.DB.Collection("Notice")
	DB.CTopMenus = DB.DB.Collection("TopMenu")
	DelayMessage.CDelayMessage = DB.DB.Collection("DelayMessage")
	DelayMessage.CDelayErrorLog = DB.DB.Collection("DelayErrorLog")

	// 连接redis
	DB.Redis = Cache.NewRedis(&Cache.RedisOpts{
		Config.Info.RedisPath,
		"",
		0,
		200,
		20,
		0,
	})

	Gin = gin.Default()
	//r.Static("/.well-known", "./.well-known/")

	InitController("GET", "/AllItems", Api.AllItems, &DB.SModel{})
	InitController("GET", "/AllItemTime", Api.AllItemTime, &DB.SModel{})
	InitController("GET", "/AllCommodity", Api.AllCommodity, &DB.SModel{})
	InitController("GET", "/AllLine", Api.AllLine, &DB.SModel{})
	InitController("GET", "/ItemInfo", Api.ItemInfo, &DB.SModel{})
	InitController("GET", "/CommodityInfo", Api.CommodityInfo, &DB.SModel{})
	InitController("POST", "/CreateComplaint", Api.CreateComplaint, &DB.SModel{})
	InitController("GET", "/AllComplaint", Api.AllComplaint, &DB.SModel{"投诉建议", "查看所有"})
	//InitController("/CreateUser", Api.CreateUser)
	InitController("POST", "/LoginUser", Api.LoginUser, &DB.SModel{})
	InitController("POST", "/UpdateUser", Api.UpdateUser, &DB.SModel{"用户管理", "修改"})
	InitController("GET", "/UserInfo", Api.UserInfo, &DB.SModel{"用户管理", "查看单条"})
	InitController("GET", "/ScenicInfo", Api.ScenicInfo, &DB.SModel{})
	InitController("GET", "/LineInfo", Api.LineInfo, &DB.SModel{})
	InitController("GET", "/AllTag", Api.AllTag, &DB.SModel{})
	InitController("GET", "/AllTagGroup", Api.AllTagGroup, &DB.SModel{})
	InitController("POST", "/Tag/Create", Api.CreateTag, &DB.SModel{"标签管理", "增加"})
	InitController("POST", "/Tag/Remove", Api.RemoveTag, &DB.SModel{"标签管理", "删除"})

	InitController("POST", "/Upload", Api.Upload, &DB.SModel{})
	InitController("POST", "/UpdateItem", Api.UpdateItem, &DB.SModel{"项目管理", "修改"})
	InitController("POST", "/UpdateCommodity", Api.UpdateCommodity, &DB.SModel{"商品管理", "修改"})
	InitController("POST", "/UpdateLine", Api.UpdateLine, &DB.SModel{"线路管理", "修改"})
	InitController("POST", "/UpdateScenic", Api.UpdateScenic, &DB.SModel{"景区管理", "修改"})
	InitController("POST", "/UpdateItemTime", Api.UpdateItemTime, &DB.SModel{"项目管理", "修改等候时间"})
	InitController("GET", "/AllScenic", Api.AllScenic, &DB.SModel{})
	InitController("POST", "/UserLog", Api.UserLog, &DB.SModel{})
	InitController("GET", "/AllUserLog", Api.AllUserLog, &DB.SModel{})
	InitController("POST", "/Sms/Send", Api.Send, &DB.SModel{})
	InitController("POST", "/Investigation/Save", Api.SaveInvestigation, &DB.SModel{})
	InitController("GET", "/Investigation/List", Api.AllInvestigation, &DB.SModel{})
	InitController("POST", "/Trajectory/Save", Api.SaveTrajectory, &DB.SModel{})
	InitController("POST", "/DealyMessage/Create", Api.CreateDealyMessage, &DB.SModel{"通知管理", "增加"})
	InitController("GET", "/DealyMessage/Info", Api.DealyMessageInfo, &DB.SModel{"通知管理", "查看所有"})
	InitController("POST", "/DealyMessage/Remove", Api.RemoveDealyMessage, &DB.SModel{"通知管理", "删除"})
	InitController("POST", "/Notice/Create", Api.CreateNotice, &DB.SModel{"公告管理", "增加"})
	InitController("GET", "/Notice/Info", Api.NoticeInfo, &DB.SModel{})
	InitController("GET", "/Notice/List", Api.NoticeList, &DB.SModel{})
	InitController("POST", "/Notice/Remove", Api.RemoveNotice, &DB.SModel{"公告管理", "删除"})
	InitController("POST", "/Notice/Modify", Api.ModifyNotice, &DB.SModel{"公告管理", "修改"})
	InitController("POST", "/Icon/Update", Api.UpdateIcon, &DB.SModel{"图标管理", "修改管理"})
	InitController("GET", "/Icon/All", Api.AllIcons, &DB.SModel{})
	InitController("GET", "/Icon/Info", Api.IconInfo, &DB.SModel{})
	InitController("POST", "/CheckToken", Api.CheckToken, &DB.SModel{})
	//InitController("/Tiles", Api.Tiles)
	InitController("POST", "/TopMenus/Update", Api.UpdateTopMenus, &DB.SModel{"菜单管理","修改"})
	InitController("POST", "/TopMenus/Remove", Api.RemoveTopMenus, &DB.SModel{"菜单管理","删除"})
	InitController("GET", "/TopMenus/All", Api.AllTopMenus, &DB.SModel{})
	InitController("GET", "/RegisterDevice", Api.RegisterDevice, &DB.SModel{})
	InitController("POST", "/RemoveUser", Api.RemoveUser, &DB.SModel{"用户管理", "删除"})

	InitController("POST", "/LoginOperator", Api.LoginOperator, &DB.SModel{})
	InitController("POST", "/UpdateOperator", Api.UpdateOperator, &DB.SModel{"操作员管理", "增加和修改"})
	InitController("GET", "/AllOperator", Api.AllOperator, &DB.SModel{"操作员管理", "查看所有"})
	InitController("GET", "/SystemInfo", Api.SystemInfo, &DB.SModel{})


	Gin.GET("/AllModules", Auth.Modules)
	//InitController("/ws", Api.WsPage)

	// 用于给赵翔测试通知效果
	Gin.GET("/PushNoticeToiOS", Api.PushNoticeToiOS)

	Gin.Static("/Upload", "./Upload")
	Gin.Static("/Console", "./Console")
	Gin.Static("/Policy", dir+"/Policy")

	Gin.GET("MP_verify_R9xuhLXYcVbdDDNk.txt", func(c *gin.Context) {
		c.String(200, "R9xuhLXYcVbdDDNk")
	})
	//r.Static("/tiles2", dir+"/tiles")
	// go Ws.Manager.Start()

	// 创建延迟消息
	DelayMessage.GlobalDM = DelayMessage.NewDelayMessage()

	go func() {
		DelayMessage.GlobalDM.Start()
	}()

	// -初始化延迟数据
	if cur, err := DelayMessage.CDelayMessage.Find(tools.GetContext(), bson.M{}); err == nil {
		defer cur.Close(tools.GetContext())
		for cur.Next(tools.GetContext()) {
			var message DelayMessage.Message
			err := cur.Decode(&message)
			tools.CheckError(err)

			nowTimeU := time.Now().Unix()
			iDelayTIme := message.DelayTime - nowTimeU

			if iDelayTIme < 0 {
				iDelayTIme = 1
			}
			DelayMessage.GlobalDM.AddTask(time.Now().Add(time.Second*time.Duration(iDelayTIme)), DelayMessage.Callback, &message)
			log.Println("增加提醒任务", message)
		}
	} else {
		spew.Dump(err)
	}

	// 默认情况使用配置文件中的端口号,除非在启动命令中指定-port :808x
	_port := Config.Info.ServerPort
	if runPort != ""{
		_port = runPort
	}
	Gin.Run(_port)
}

func InitController(method string, uri string, handFunc func(c *gin.Context), auth *DB.SModel) {

	if auth.Model != "" {
		Auth.Models[auth.Model] = append(Auth.Models[auth.Model], auth.Action)
	}

	if method == "GET" {
		Gin.GET(uri, Auth.CheckAuthFunc(handFunc, auth))
	}
	if method == "POST" {
		Gin.POST(uri, Auth.CheckAuthFunc(handFunc, auth))
	}
}