105 lines
2.8 KiB
Go
105 lines
2.8 KiB
Go
package controllers
|
||
|
||
import (
|
||
"bytes"
|
||
"encoding/json"
|
||
"io"
|
||
"strconv"
|
||
"strings"
|
||
|
||
"server/pkg/jwtutil"
|
||
|
||
beego "github.com/beego/beego/v2/server/web"
|
||
)
|
||
|
||
// =============================================================
|
||
// 平台官网管理(/platform/website/*)公共工具
|
||
// 数据表前缀 yz_platform_website_,建表见 docs/sql/create_platform_website.sql
|
||
// =============================================================
|
||
|
||
// websiteAuth 平台管理员鉴权,失败时已写出错误响应,返回 ok=false
|
||
func websiteAuth(c *beego.Controller) (*jwtutil.Claims, bool) {
|
||
claims, err := requirePlatform(c)
|
||
if err != nil {
|
||
jsonErr(c, 401, 401, err.Error())
|
||
return nil, false
|
||
}
|
||
return claims, true
|
||
}
|
||
|
||
// websiteOK 统一成功响应:{ code:200, msg:"success", data:... }
|
||
func websiteOK(c *beego.Controller, data interface{}) {
|
||
c.Data["json"] = map[string]interface{}{"code": 200, "msg": "success", "data": data}
|
||
_ = c.ServeJSON()
|
||
}
|
||
|
||
// websitePaging 解析分页参数:page 默认 1,pageSize 默认 10(兼容 limit),上限 200
|
||
func websitePaging(c *beego.Controller) (int, int) {
|
||
page, _ := c.GetInt("page", 1)
|
||
pageSize, _ := c.GetInt("pageSize", 0)
|
||
if pageSize <= 0 {
|
||
pageSize, _ = c.GetInt("limit", 0)
|
||
}
|
||
if page < 1 {
|
||
page = 1
|
||
}
|
||
if pageSize < 1 {
|
||
pageSize = 10
|
||
}
|
||
if pageSize > 200 {
|
||
pageSize = 200
|
||
}
|
||
return page, pageSize
|
||
}
|
||
|
||
// websiteID 解析路径参数 :id
|
||
func websiteID(c *beego.Controller) (uint64, bool) {
|
||
id, err := strconv.ParseUint(c.Ctx.Input.Param(":id"), 10, 64)
|
||
if err != nil || id == 0 {
|
||
jsonErr(c, 400, 400, "无效ID")
|
||
return 0, false
|
||
}
|
||
return id, true
|
||
}
|
||
|
||
// websiteIntParam 解析整型查询参数,未传或非法时返回 -1(表示不过滤)
|
||
func websiteIntParam(c *beego.Controller, key string) int {
|
||
raw := strings.TrimSpace(c.GetString(key))
|
||
if raw == "" {
|
||
return -1
|
||
}
|
||
v, err := strconv.Atoi(raw)
|
||
if err != nil {
|
||
return -1
|
||
}
|
||
return v
|
||
}
|
||
|
||
// websiteStatusParam 解析 status 查询参数,未传时返回 -1(表示不过滤)
|
||
func websiteStatusParam(c *beego.Controller) int {
|
||
return websiteIntParam(c, "status")
|
||
}
|
||
|
||
// websiteBind 解析 JSON 请求体到 target,失败时已写出 400
|
||
func websiteBind(c *beego.Controller, target interface{}) bool {
|
||
body, err := io.ReadAll(c.Ctx.Request.Body)
|
||
if err != nil {
|
||
jsonErr(c, 400, 400, "参数错误")
|
||
return false
|
||
}
|
||
if err = json.Unmarshal(body, target); err != nil {
|
||
jsonErr(c, 400, 400, "参数错误")
|
||
return false
|
||
}
|
||
return true
|
||
}
|
||
|
||
// websiteBindOptional 宽松解析请求体:body 为空或非法时不作响应,调用方按零值处理
|
||
func websiteBindOptional(c *beego.Controller, target interface{}) {
|
||
body, err := io.ReadAll(c.Ctx.Request.Body)
|
||
if err != nil || len(bytes.TrimSpace(body)) == 0 {
|
||
return
|
||
}
|
||
_ = json.Unmarshal(body, target)
|
||
}
|