算了,后端我自己写吧

This commit is contained in:
2026-04-01 12:09:02 +08:00
parent 4138340f53
commit 1a0a01a56d
69 changed files with 1949 additions and 102 deletions
+62
View File
@@ -0,0 +1,62 @@
package routers
import (
"encoding/json"
"fmt"
"os"
"github.com/gin-gonic/gin"
)
var ErrorCode map[string]interface{}
func init() {
//读取默认配置
fmt.Println("尝试读取错误码文件")
data, err := os.ReadFile("./defConfig/errorCodes.json")
if err != nil {
fmt.Println("读取错误码文件失败", err)
}
if err := json.Unmarshal(data, &ErrorCode); err != nil {
fmt.Println("解析错误码文件失败", err)
}
}
// 把数据分离成cookie和json
func SeparateData(ctx *gin.Context) (map[string]interface{}, string) {
var jsonData map[string]interface{}
if err := ctx.ShouldBindJSON(&jsonData); err == nil {
//分离数据
cookie, ok := jsonData["userCookieValue"].(string)
if !ok {
cookie = ""
}
data, ok := jsonData["data"].(map[string]interface{})
if !ok {
data = nil
}
return data, cookie
}
return nil, ""
}
func ApiRoot(r *gin.RouterGroup) {
ApiStatic(r.Group("/static"))
ApiUser(r.Group("/users"))
ApiFiles(r.Group("/files"))
ApiPurchase(r.Group("/purchase"))
r.GET("/", func(ctx *gin.Context) {
ReturnJson(ctx, "apiOK", nil)
})
}
+179
View File
@@ -0,0 +1,179 @@
package routers
import (
"encoding/json"
"fmt"
"ops/models"
"github.com/gin-gonic/gin"
"github.com/mitchellh/mapstructure"
"gorm.io/datatypes"
)
type CostItem struct {
Cost int `json:"cost"` // 必须,非负
CostT int `json:"costt"` // 必须,非负
CurrencyType string `json:"currencytype"` // 必须
Int int `json:"int"` // 必须
Type string `json:"type"` // 必须
}
type From_purchase_addorder struct {
Costs []CostItem `json:"costs"` //
Link string `json:"link"` // 可选
OrderStatus string `json:"order_status"` //
PartName string `json:"partname"` // 可选
Photos []string `json:"photos"` // 可选
Remark string `json:"remark"` // 可选
Styles string `json:"styles"` // 可选
Title string `json:"title"` // 必须
TrackingNumber string `json:"tracking_number"` // 可选
UpdateTime string `json:"update_time"` // 可选
}
func ApiPurchase(r *gin.RouterGroup) {
r.POST("/getorders", func(ctx *gin.Context) {
isAuth, user, data := AuthenticationAuthority(ctx)
if isAuth {
fmt.Println(user)
// DebugPrintJson(data)
type From_purchase_getorders struct {
Search string
Entries int
Page int
}
var jsondata From_purchase_getorders
if err := mapstructure.Decode(data, &jsondata); err == nil {
//fmt.Println(jsondata)
is_data_ok := true
if jsondata.Entries <= 0 || jsondata.Entries > 300 {
is_data_ok = false
}
if jsondata.Page <= 0 {
is_data_ok = false
}
if is_data_ok {
//读取有多少条目
var count int64
models.DB.Model(&models.TabPurchaseOrder{}).Count(&count)
//fmt.Println(count)
//读取条目
var getorders []models.TabPurchaseOrder
models.DB.Order("created_at DESC").Offset(jsondata.Entries * (jsondata.Page - 1)).Limit(jsondata.Entries).Find(&getorders)
ReturnJson(ctx, "apiOK", map[string]interface{}{
"all_count": count,
"all_orders": getorders,
})
} else {
ReturnJson(ctx, "jsonErr", nil)
}
} else {
ReturnJson(ctx, "jsonErr", nil)
}
} else {
ReturnJson(ctx, "userCookieError", nil)
}
})
r.POST("/addorder", func(ctx *gin.Context) {
isAuth, user, data := AuthenticationAuthority(ctx)
if isAuth {
//需要处理提交的数据,接口有固定的数据格式,不允许乱搞
//fmt.Println(isAuth)
//fmt.Println(user)
//DebugPrintJson(data)
var jsondata From_purchase_addorder
if err := mapstructure.Decode(data, &jsondata); err == nil {
//fmt.Println("转换后数据:\n", jsondata)
//数据比较混乱 在这里校验
//判断标题不为空
is_data_ok := true
if jsondata.Title == "" {
is_data_ok = false
}
//判断数量与价格是否为负数
for i := 0; i < len(jsondata.Costs); i++ {
if jsondata.Costs[i].Cost <= 0 {
is_data_ok = false
}
if jsondata.Costs[i].Int <= 0 {
is_data_ok = false
}
}
//判断图片是否为哈希值
for i := 0; i < len(jsondata.Photos); i++ {
//判断字符串是否包含标点符号
if models.IsContainsSpecialChar(jsondata.Photos[i]) {
is_data_ok = false
}
}
//判断时间字符串是否合法
uptime, e := models.StringToTimePtr(jsondata.UpdateTime)
if e != nil {
is_data_ok = false
}
if is_data_ok {
//校验通过
//载入数据库
photos, _ := json.Marshal(jsondata.Photos) //把图片数组转换成字符串
new_data := models.TabPurchaseOrder{
UserID: user.ID,
Title: jsondata.Title,
Remark: jsondata.Remark,
Photos: datatypes.JSON(photos),
Link: jsondata.Link,
PartName: jsondata.PartName,
Styles: jsondata.Styles,
UpdateTime: uptime,
TrackingNumber: jsondata.TrackingNumber,
OrderStatus: jsondata.OrderStatus,
}
models.DB.Create(&new_data)
for i := 0; i < len(jsondata.Costs); i++ {
new_cost_data := models.TabPurchaseCosts{
Price: jsondata.Costs[i].Cost,
Quantity: jsondata.Costs[i].Int,
UserID: user.ID,
OrderID: new_data.ID,
}
models.DB.Create(&new_cost_data)
}
} else {
ReturnJson(ctx, "jsonErr", nil)
}
} else {
ReturnJson(ctx, "jsonErr", nil)
}
} else {
ReturnJson(ctx, "userCookieError", nil)
}
ReturnJson(ctx, "apiErr", nil)
})
}
+25
View File
@@ -0,0 +1,25 @@
package routers
import (
"ops/models"
"path"
"github.com/gin-gonic/gin"
)
//处理api的静态内容
func ApiStatic(r *gin.RouterGroup) {
r.GET("/avatar/:filename", func(ctx *gin.Context) {
filename := ctx.Param("filename")
dst := path.Join(models.ConfigsFile.Pahts["avatar"], filename)
if models.FileExists(dst) {
ctx.File(dst)
} else {
//找不到文件
ctx.String(404, "file not found")
}
})
}
+541
View File
@@ -0,0 +1,541 @@
package routers
import (
"errors"
"fmt"
"ops/models"
"path"
"strconv"
"time"
"github.com/gin-gonic/gin"
"github.com/mitchellh/mapstructure"
)
func ApiInit() {
//用户模块初始化init
fmt.Println("users init")
//创建admin用户
var user models.TabUser_
user.Name = "admin"
if models.DB.Where(&user).First(&user).Error == nil {
} else {
//fmt.Println("用户不存在")
//对密码加盐
user.Salt = models.RandStr32()
user.Pass = "adminpassword"
models.HashUserPass(&user)
models.DB.Create(&user) // 传入指针
}
//创建admin group
var usergroup models.TabUserGroups_
usergroup.Name = "admins"
if models.DB.Where(&usergroup).First(&usergroup).Error == nil {
} else {
fmt.Println("用户组不存在")
models.DB.Create(&usergroup) // 传入指针
}
//创建用户与用户组绑定
var usergroupbind models.TabUserGroupBinds_
usergroupbind.UserID = user.ID
usergroupbind.GroupID = usergroup.ID
if models.DB.Where(&usergroupbind).First(&usergroupbind).Error == nil {
} else {
models.DB.Create(&usergroupbind) // 传入指针
}
}
type From_user_add struct {
Useremail string `json:"useremail"`
Username string `json:"username"`
Userpass string `json:"userpass"`
}
type From_user_login struct {
Username string `json:"username"`
Userpass string `json:"userpass"`
Remember bool `json:"remember"`
}
type From_user_updateinfo struct {
Username string `json:"username"`
Remark string `json:"remark"`
Birthday string `json:"birthday"`
}
type From_user_changeemail struct {
Newemail string `json:"newemail"`
}
type From_user_changepass struct {
Oldpass string `json:"oldpass"`
Newpass string `json:"newpass"`
}
func AuthenticationAuthorityFromCookie(c string) (*models.TabUser_, error) {
if c != "" {
cookie := models.TabCookie_{
Value: c,
}
if models.DB.Where(&cookie).First(&cookie).Error == nil {
//找到cookie,验证cookie有效性,以及更新cookie
if models.CheckCookiesAndUpdate(&cookie) {
//cookie有效
//载入user
user := models.TabUser_{
ID: cookie.UserID,
}
models.DB.Where(&user).First(&user)
return &user, nil
} else {
return nil, errors.New("cookie 过期")
}
} else {
return nil, errors.New("cookie Not Fund")
}
} else {
return nil, errors.New("cookie 参数错误")
}
}
func AuthenticationAuthority(ctx *gin.Context) (bool, models.TabUser_, map[string]interface{}) {
var user models.TabUser_
data, cookieval := SeparateData(ctx)
//fmt.Println("cookieis" + cookieval)
if cookieval != "" {
cookie := models.TabCookie_{
Value: cookieval,
}
if models.DB.Where(&cookie).First(&cookie).Error == nil {
//找到cookie,验证cookie有效性,以及更新cookie
if models.CheckCookiesAndUpdate(&cookie) {
//cookie有效
//载入user
user := models.TabUser_{
ID: cookie.UserID,
}
models.DB.Where(&user).First(&user)
return true, user, data
} else {
ReturnJson(ctx, "userCookieExpired", nil)
return false, user, nil
}
} else {
ReturnJson(ctx, "userCookieNotFund", nil)
return false, user, nil
}
} else {
ReturnJson(ctx, "userCookieError", nil)
return false, user, nil
}
//return false, user
}
func ApiUser(r *gin.RouterGroup) {
r.GET("/test", func(ctx *gin.Context) {
ReturnJson(ctx, "apiOK", nil)
})
r.POST("/test", func(ctx *gin.Context) {
ReturnJson(ctx, "apiOK", nil)
})
//修改用户密码
r.POST("/changePassword", func(ctx *gin.Context) {
isAuth, user, data := AuthenticationAuthority(ctx)
if isAuth {
var jsonData From_user_changepass
if err := mapstructure.Decode(data, &jsonData); err == nil {
//验证旧密码
fmt.Println(user)
//转换旧密码
olduser := models.TabUser_{
Pass: jsonData.Oldpass,
Salt: user.Salt,
}
models.HashUserPass(&olduser)
if olduser.Pass == user.Pass {
//旧密码正确,更新新密码
var userupdate models.TabUser_
userupdate.Pass = jsonData.Newpass
userupdate.Salt = models.RandStr32()
models.HashUserPass(&userupdate)
models.DB.Model(&user).Updates(&userupdate)
ReturnJson(ctx, "apiOK", nil)
} else {
//旧密码错误
ReturnJson(ctx, "userPassIncorrect", nil)
}
} else {
ReturnJson(ctx, "jsonErr", nil)
}
}
})
//更新用户邮箱
r.POST("/changeEmail", func(ctx *gin.Context) {
isAuth, user, data := AuthenticationAuthority(ctx)
if isAuth {
var jsonData From_user_changeemail
if err := mapstructure.Decode(data, &jsonData); err == nil {
//判断新邮箱格式
if models.IsEmailValid(jsonData.Newemail) {
var userupdate models.TabUser_
userupdate.Email = jsonData.Newemail
models.DB.Model(&user).Updates(&userupdate)
ReturnJson(ctx, "apiOK", nil)
} else {
ReturnJson(ctx, "userEmailFormatError", nil)
}
} else {
ReturnJson(ctx, "jsonErr", nil)
}
}
})
//修改用户头像
r.POST("/updateAvatar", func(ctx *gin.Context) {
cookie := ctx.PostForm("cookie")
user, err := AuthenticationAuthorityFromCookie(cookie)
if err == nil {
file, err := ctx.FormFile("file")
if err == nil {
if file.Filename != "" {
//限制文件大小
if file.Size > 512 {
//头像裁剪过限制1M应该差不多
if file.Size < 1048576 {
//判断mime
mimeType, err := models.GetFileMime(file)
if err == nil {
file_extname := models.ConfigsFile.AllowImageMime[mimeType]
if file_extname != "" {
//haxi文件
file_hashi_name, err := models.SHA256HashFile(file)
if err == nil {
dst := path.Join(models.ConfigsFile.Pahts["avatar"], file_hashi_name+file_extname)
var is_save_ok = false
//判断文件是否存在避免重复保存
if models.FileExists(dst) {
//fmt.Println("文件存在")
is_save_ok = true
ReturnJson(ctx, "apiOK", nil)
} else {
//fmt.Println("文件no存在")
ferr := ctx.SaveUploadedFile(file, dst)
if ferr == nil {
//文件保存成功
//fmt.Print("save_ok")
is_save_ok = true
ReturnJson(ctx, "apiOK", nil)
} else {
fmt.Print(ferr)
ReturnJson(ctx, "postErr", nil)
}
}
if is_save_ok {
//修改数据库内容
var user_info_fund models.TabUserInfo_
user_info_fund.UserID = user.ID
var user_update_avatar models.TabUserInfo_
user_update_avatar.AvatarPath = file_hashi_name + file_extname
models.DB.Where(&user_info_fund).Updates(&user_update_avatar)
}
} else {
ReturnJson(ctx, "postErr", nil)
}
} else {
ReturnJson(ctx, "file_mime_err", nil)
}
} else {
ReturnJson(ctx, "postErr", nil)
}
} else {
ReturnJson(ctx, "file_size_err", nil)
}
} else {
ReturnJson(ctx, "file_size_err", nil)
}
} else {
ReturnJson(ctx, "file_name_err", nil)
}
} else {
ReturnJson(ctx, "file_get_err", nil)
}
} else {
ReturnJson(ctx, "userCookieError", nil)
}
})
//更新用户info
r.POST("/updateInfo", func(ctx *gin.Context) {
isAuth, user, data := AuthenticationAuthority(ctx)
if isAuth {
var jsonData From_user_updateinfo
if err := mapstructure.Decode(data, &jsonData); err == nil {
// fmt.Println("updateinfo data is", jsonData)
// fmt.Println(user)
t, err := time.Parse("2006-01-02", jsonData.Birthday)
if err == nil {
var userinfo models.TabUserInfo_
userinfo.UserID = user.ID
var userinfoupdate models.TabUserInfo_
userinfoupdate.UserID = user.ID
userinfoupdate.CreatedAt = time.Now()
userinfoupdate.Username = jsonData.Username
userinfoupdate.Birthdate = t
userinfoupdate.FirstName = jsonData.Remark
//先查找是否有记录
if models.DB.Where(&userinfo).First(&userinfo).Error == nil {
//有记录,更新
models.DB.Model(&userinfo).Updates(&userinfoupdate)
} else {
//无记录,创建
models.DB.Create(&userinfoupdate) // 传入指针
}
ReturnJson(ctx, "apiOK", nil)
} else {
ReturnJson(ctx, "jsonErr", nil)
}
} else {
ReturnJson(ctx, "jsonErr", nil)
}
}
})
//通过cookie获取用户info
r.POST("/getinfo", func(ctx *gin.Context) {
isAuth, user, _ := AuthenticationAuthority(ctx)
if isAuth {
//载入用户info
var userinfo models.TabUserInfo_
userinfo.UserID = user.ID
//fmt.Println(userInfo)
var redata map[string]interface{} = make(map[string]interface{})
if models.DB.Where(&userinfo).First(&userinfo).Error == nil {
redata["userInfo"] = userinfo
} else {
redata["userInfo"] = nil
}
user.Pass = ""
user.Salt = ""
redata["user"] = user
ReturnJson(ctx, "apiOK", redata)
}
// _, cookieval := SeparateData(ctx)
// //fmt.Println("cookieis" + cookieval)
// if cookieval != "" {
// cookie := models.TabCookie_{
// Value: cookieval,
// }
// if models.DB.Where(&cookie).First(&cookie).Error == nil {
// //找到cookie,验证cookie有效性,以及更新cookie
// if models.CheckCookiesAndUpdate(&cookie) {
// //cookie有效
// //返回最新cookie
// redata := map[string]interface{}{
// "cookie": cookie,
// }
// //载入用户info
// userInfo := models.TabFileInfo_{
// UserID: cookie.UserID,
// }
// if models.DB.Where(&userInfo).First(&userInfo).Error == nil {
// redata["userInfo"] = userInfo
// } else {
// redata["userInfo"] = nil
// }
// //载入user
// user := models.TabUser_{
// ID: cookie.UserID,
// }
// models.DB.Where(&user).First(&user)
// user.Pass = ""
// user.Salt = ""
// redata["user"] = user
// ReturnJson(ctx, "apiOK", redata)
// } else {
// ReturnJson(ctx, "userCookieExpired", nil)
// }
// } else {
// ReturnJson(ctx, "userCookieNotFund", nil)
// }
// } else {
// ReturnJson(ctx, "userCookieError", nil)
// }
})
//用户登陆
r.POST("/login", func(ctx *gin.Context) {
var loginuser From_user_login
data, _ := SeparateData(ctx)
if data != nil {
if err := mapstructure.Decode(data, &loginuser); err == nil {
if loginuser.Username != "" && loginuser.Userpass != "" {
//传入的数据都ok,获取用户信息
getuser := models.TabUser_{
Name: loginuser.Username,
}
if models.DB.Where(&getuser).First(&getuser).Error == nil {
//倒入数据
user := models.TabUser_{
Pass: loginuser.Userpass, //密码明文
Salt: getuser.Salt, //保存的盐制
}
//哈希密
models.HashUserPass(&user)
if user.Pass == getuser.Pass {
//用户密码正确,生成cookie
cookie := models.TabCookie_{
UserID: getuser.ID,
Name: "login",
Value: models.RandStr32(),
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
ExpiresAt: time.Now().Add(time.Duration(models.ConfigsUser.CookieTimeout) * time.Second), //计算过期时间,
Remember: loginuser.Remember,
}
models.DB.Create(&cookie) // 传入指针
redata := map[string]interface{}{
"cookie": cookie,
}
ReturnJson(ctx, "apiOK", redata)
} else {
ReturnJson(ctx, "userPassIncorrect", nil)
}
} else {
//用户不存在
ReturnJson(ctx, "userNameNoFund", nil)
}
} else {
ReturnJson(ctx, "jsonErr", nil)
}
} else {
ReturnJson(ctx, "jsonErr", nil)
}
} else {
ReturnJson(ctx, "postErr", nil)
}
})
//用户注册
r.POST("/register", func(ctx *gin.Context) {
//转换传进来的数据
var jsonData From_user_add
data, _ := SeparateData(ctx)
if data != nil {
if err := mapstructure.Decode(data, &jsonData); err == nil {
//转换字段
newUser := models.TabUser_{
Name: jsonData.Username,
Email: jsonData.Useremail,
Pass: jsonData.Userpass, // 实际应替换为哈希值
Date: time.Now(),
// Date 字段无需赋值,数据库会自动填充默认值
}
if newUser.Name != "" && newUser.Pass != "" && newUser.Email != "" {
//用户名是唯一的,先读取是否有这个用户名
var user models.TabUser_
user.Name = newUser.Name
if models.DB.Where(&user).First(&user).Error == nil {
//fmt.Println("找到用户:", user.ID)
ReturnJson(ctx, "userNameDup", nil)
} else {
//fmt.Println("用户不存在")
//对密码加盐
newUser.Salt = models.RandStr32()
//对用户的密码进行哈希替换
models.HashUserPass(&newUser)
models.DB.Create(&newUser) // 传入指针
//创建用户后写一个log
models.LogAdd(ctx, "New user id:"+strconv.Itoa(int(newUser.ID)))
ReturnJson(ctx, "apiOK", nil)
}
} else {
ReturnJson(ctx, "jsonErr", nil)
}
} else {
ReturnJson(ctx, "jsonErr", nil)
}
} else {
ReturnJson(ctx, "postErr", nil)
}
})
}
+174
View File
@@ -0,0 +1,174 @@
package routers
import (
"io"
"net/http"
"ops/models"
"path"
"path/filepath"
"github.com/gin-gonic/gin"
)
func file_save() {
}
func ApiFiles(r *gin.RouterGroup) {
//getfile := r.Group("/get") //定义上传组
r.GET("/:mode/:hash", func(ctx *gin.Context) {
hash := ctx.Param("hash")
mode := ctx.Param("mode")
// filename := ctx.Param("filename")
// fmt.Println(filename)
download := false
isPartOK := false
if mode == "get" {
isPartOK = true
download = true
}
if mode == "download" {
isPartOK = true
download = false
}
if isPartOK {
file_info := models.TabFileInfo_{
Sha256: hash,
}
if models.DB.Where(&file_info).First(&file_info).Error == nil {
ReturnFile(ctx, &file_info, download)
} else {
//fmt.Println("not fund")
ReturnJson(ctx, "file_not_found", nil)
}
} else {
ReturnJson(ctx, "file_part_err", nil)
}
})
upload := r.Group("/upload") //定义上传组
//上传文件的总接口,能上传什么文件应该由后端决定,前端仅做相应限制
upload.POST("/image", func(ctx *gin.Context) {
cookie := ctx.PostForm("cookie") //首先需要判断用户是否登录
//通过cookie获取用户信息
user, err := AuthenticationAuthorityFromCookie(cookie)
if err == nil {
file, err := ctx.FormFile("file")
if err == nil {
if file.Filename != "" {
//限制文件大小
if file.Size > 512 {
if file.Size < int64(models.ConfigsFile.MaxSize) {
//判断文件mime是否合法
// 打开文件流
src_mime, _ := file.Open()
defer src_mime.Close()
// 读取前512字节用于MIME检测
buffer := make([]byte, 512)
io.ReadFull(src_mime, buffer)
// 检测MIME类型
mimeType := http.DetectContentType(buffer)
file_extname := models.ConfigsFile.AllowImageMime[mimeType]
if file_extname != "" {
filename := filepath.Base(file.Filename) // 防御性处理路径分隔符
// 计算哈希值
hash_str, err := models.SHA256HashFile(file)
if err == nil {
//fmt.Println(hash_str)
//fmt.Println(filename)
//这是上传的真实路径
dst := path.Join(models.ConfigsFile.Pahts["image"], hash_str)
//fmt.Println(dst)
//判断文件是否存在避免重复保存
if models.FileExists(dst) {
//fmt.Println("文件存在")
} else {
//fmt.Println("文件no存在")
ferr := ctx.SaveUploadedFile(file, dst)
if ferr == nil {
//文件保存成功
} else {
ReturnJson(ctx, "file_save_err", nil)
ctx.Abort() //end
return
}
}
//记录到数据库
//先检查数据库有没有数据
fund_file_info := models.TabFileInfo_{
Name: filename,
Sha256: hash_str,
Mime: mimeType,
Type: "image",
UserID: user.ID,
}
fund_file_info2 := models.TabFileInfo_{}
models.DB.Where(&fund_file_info).Find(&fund_file_info2)
if fund_file_info2.ID != 0 {
fund_file_info2.Const += 1
models.DB.Where(&fund_file_info).Updates(&fund_file_info2)
} else {
fund_file_info.Path = dst
models.DB.Create(&fund_file_info) // 传入指针
}
//返回后台存储的URL
download_URL := path.Join("/api/files/download/", hash_str)
get_URL := path.Join("/api/files/get/", hash_str)
re := map[string]interface{}{
"download": download_URL,
"get": get_URL,
"hash": hash_str,
}
ReturnJson(ctx, "apiOK", re)
} else {
ReturnJson(ctx, "file_hash_err", nil)
}
} else {
ReturnJson(ctx, "file_mime_err", nil)
}
} else {
ReturnJson(ctx, "file_size_err", nil)
}
} else {
ReturnJson(ctx, "file_size_err", nil)
}
} else {
ReturnJson(ctx, "file_name_err", nil)
}
} else {
ReturnJson(ctx, "file_get_err", nil)
}
} else {
ReturnJson(ctx, "userCookieError", nil)
}
//ReturnJson(ctx, "apiErr", nil)
})
// r.GET("/upload", func(ctx *gin.Context) {
// ReturnJson(ctx, "apiOK", nil)
// })
}
+46
View File
@@ -0,0 +1,46 @@
package routers
import (
"encoding/json"
"fmt"
"ops/models"
"github.com/gin-gonic/gin"
)
func DebugPrintJson(data map[string]interface{}) {
p, _ := json.MarshalIndent(data, "", " ")
fmt.Println("\n", string(p))
}
func ReturnJson(ctx *gin.Context, errMsg string, data map[string]interface{}) {
var errCode = ErrorCode[errMsg]
returnData := map[string]interface{}{}
// cookie, have_cookie := ctx.Get("cookie")
// if have_cookie {
// returnData["cookie"] = cookie
// }
returnData["err_code"] = errCode
returnData["err_msg"] = errMsg
if data != nil {
returnData["return"] = data
}
ctx.JSON(200, &returnData)
//ctx.Abort()
}
func ReturnFile(ctx *gin.Context, file_info *models.TabFileInfo_, preview bool) {
if preview {
ctx.File(file_info.Path)
} else {
//需要从数据库拉取原始文件名
ctx.FileAttachment(file_info.Path, file_info.Name)
}
}