package v1 import ( "designs/app/common/response" "designs/global" "designs/model" "fmt" "github.com/gin-gonic/gin" "time" ) func TestSetOnline(c *gin.Context) { err := SetOnline("test222", "wx", 1, 1234, time.Now()) if err != nil { response.Fail(c, 1001, err.Error()) return } response.Success(c, gin.H{}) } func TestDelete(c *gin.Context) { ////读取前一日数据 //now := time.Now() // //for i := 30; i <= 40; i++ { // last := now.AddDate(0, 0, -i).Format("2006-01-02") // // path := "storage" + "/" + last // // //删除前一天的文件夹 // err := os.RemoveAll(path) // if err != nil { // fmt.Println("删除文件夹失败:"+path, err) // } else { // fmt.Println("删除文件夹完成:" + path) // } //} //获取到表名 now := time.Now() date := now.AddDate(0, 0, -29).Format("20060102") tableName := "user_online_" + date var tableList []string sql := "SELECT table_name FROM information_schema.tables WHERE table_schema = 'chunhao' AND table_name LIKE '" + tableName + "%'" err := global.App.DB.Raw(sql).Pluck("table_name", &tableList).Error if err != nil { global.App.Log.Error("查询", date, "user_online数据表失败", err.Error()) return } //批量删除数据表 for _, table := range tableList { sql := "drop table IF EXISTS " + table err := global.App.DB.Exec(sql).Error if err != nil { global.App.Log.Error("删除", table, "数据表失败", err.Error()) return } } fmt.Println(tableList) } func SetOnline(gid string, pf string, types int, userId int, now time.Time) error { //先根据date ,gid ,判定存哪个表 date := now.Format("20060102") tableName := "user_online" + "_" + date + "_" + gid //先尝试写入,如果写入失败证明表不存在,则创建表然后写入 userOnline := model.UserOnlineSplit{ Pf: pf, UserId: userId, LogTime: now, Type: types, } err := global.App.DB.Table(tableName).Create(&userOnline).Error if err != nil { err := global.App.DB.Exec(` CREATE TABLE IF NOT EXISTS ` + tableName + ` ( id int unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', pf varchar(5) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '登录路径', userId int NOT NULL COMMENT '用户ID', type tinyint NOT NULL COMMENT '1:在线 2.下线', logTime timestamp NULL DEFAULT NULL COMMENT '时间', PRIMARY KEY (id) USING BTREE, KEY pf (pf) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci `).Error if err != nil { return err } err = global.App.DB.Table(tableName).Create(&userOnline).Error if err != nil { return err } } return nil }