This commit is contained in:
孟帅
2022-11-24 23:37:34 +08:00
parent 4ffe54b6ac
commit 29bda0dcdd
1487 changed files with 97869 additions and 96539 deletions

View File

@@ -0,0 +1,85 @@
// Package cmd
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package cmd
import (
"context"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gcmd"
"github.com/gogf/gf/v2/os/grpool"
)
var (
serverCloseSignal chan struct{}
Main = &gcmd.Command{
Description: `
欢迎使用HotGo!
---------------------------------------------------------------------------------
启动服务
>> HTTP服务 [gf run main.go --args "http"]
>> 消息队列 [gf run main.go --args "queue"]
>> 所有服务 [gf run main.go --args "all"]
---------------------------------------------------------------------------------
工具
>> 释放casbin权限用于清理无效的权限设置 [gf run main.go --args "tools -m=casbin -a1=refresh"]
`,
}
Help = &gcmd.Command{
Name: "help",
Brief: "查看帮助",
Description: `
欢迎使用 HotGo
当前版本:v2.0.0
`,
}
All = &gcmd.Command{
Name: "all",
Brief: "start all server",
Description: "this is the command entry for starting all server",
Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
g.Log().Info(ctx, "start all server")
if err = grpool.AddWithRecover(ctx, func(ctx context.Context) {
if err := Http.Func(ctx, parser); err != nil {
g.Log().Fatal(ctx, "http server start fail:", err)
}
}); err != nil {
return
}
if err = grpool.AddWithRecover(ctx, func(ctx context.Context) {
if err := Queue.Func(ctx, parser); err != nil {
g.Log().Fatal(ctx, "queue consumer start fail:", err)
}
}); err != nil {
g.Log().Fatal(ctx, "queue consumer start fail2:", err)
return
}
// 信号监听
signalListen(ctx, signalHandlerForOverall)
select {
case <-serverCloseSignal:
// ...
}
g.Log().Info(ctx, "service successfully closed ..")
return
},
}
)
func init() {
if err := Main.AddCommand(Http, Queue, Tools, All, Help); err != nil {
panic(err)
}
serverCloseSignal = make(chan struct{}, 1)
}

View File

@@ -0,0 +1,40 @@
// Package cmd
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package cmd
import (
"context"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gproc"
"github.com/gogf/gf/v2/os/grpool"
"hotgo/internal/crons"
"hotgo/internal/websocket"
"os"
)
func signalHandlerForCron(sig os.Signal) {
crons.StopALL()
}
func signalHandlerForWebSocket(sig os.Signal) {
websocket.Stop()
}
func signalHandlerForOverall(sig os.Signal) {
serverCloseSignal <- struct{}{}
}
func signalListen(ctx context.Context, handler ...gproc.SigHandler) {
err := grpool.AddWithRecover(ctx, func(ctx context.Context) {
gproc.AddSigHandlerShutdown(handler...)
gproc.Listen()
})
if err != nil {
g.Log().Fatal(ctx, "signalListen Fatal:", err)
return
}
}

102
server/internal/cmd/http.go Normal file
View File

@@ -0,0 +1,102 @@
// Package cmd
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package cmd
import (
"context"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
"github.com/gogf/gf/v2/os/gcmd"
"hotgo/internal/library/casbin"
"hotgo/internal/model"
"hotgo/internal/router"
"hotgo/internal/service"
)
var (
Http = &gcmd.Command{
Name: "http",
Usage: "http",
Brief: "HTTP服务",
Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
if _, err := g.Cfg().Get(ctx, "hotgo.debug"); err != nil {
g.Log().Fatal(ctx, "配置读取异常:", err, "\r\n你确定 config/config.yaml 文件存在且格式正确吗?\r\n")
}
// 加载权限
casbin.InitEnforcer(ctx)
s := g.Server()
// 错误状态码接管
s.BindStatusHandler(404, func(r *ghttp.Request) {
r.Response.Writeln("404 - 你似乎来到了没有知识存在的荒原…")
})
s.BindStatusHandler(403, func(r *ghttp.Request) {
r.Response.Writeln("403 - 网站拒绝显示此网页")
})
// 请求结束事件回调
s.BindHookHandler("/*any", ghttp.HookAfterOutput, service.Hook().GlobalLog)
s.Group("/", func(group *ghttp.RouterGroup) {
// 注册全局中间件
group.Middleware(
service.Middleware().Ctx, //必须第一个加载
service.Middleware().CORS,
service.Middleware().DemoLimit,
service.Middleware().ResponseHandler,
)
// 注册默认首页路由
group.ALL("/", func(r *ghttp.Request) {
r.Response.Write("hello hotGo!!")
return
})
group.ALL("/login", func(r *ghttp.Request) {
r.Response.RedirectTo("/admin")
})
// 注册后台路由
router.Admin(ctx, group)
// 注册前台路由
router.Api(ctx, group)
// 注册websocket路由
router.WebSocket(ctx, group)
})
// 启动定时任务
service.SysCron().StartCron(ctx)
// 信号监听
signalListen(ctx, signalHandlerForCron, signalHandlerForWebSocket)
// 开启https访问
var (
sSLConfig *model.SSLConfig
ssl, _ = g.Cfg().Get(ctx, "hotgo.ssl")
)
if err := ssl.Struct(&sSLConfig); err != nil {
g.Log().Fatalf(ctx, "hotgo启动失败, ssl err:", err)
return err
}
if sSLConfig != nil && sSLConfig.Switch {
s.EnableHTTPS(sSLConfig.CrtPath, sSLConfig.KeyPath)
}
// Just run the server.
s.Run()
return nil
},
}
)

View File

@@ -0,0 +1,27 @@
// Package cmd
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package cmd
import (
"context"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gcmd"
"hotgo/internal/queues"
)
var (
Queue = &gcmd.Command{
Name: "queue",
Brief: "消息队列",
Description: ``,
Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
g.Log().Infof(ctx, "start queue consumer..")
queues.Run(ctx)
return
},
}
)

View File

@@ -0,0 +1,62 @@
// Package cmd
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package cmd
import (
"context"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gcmd"
"hotgo/internal/library/casbin"
)
var (
Tools = &gcmd.Command{
Name: "tools",
Brief: "工具",
Description: ``,
Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
flags := parser.GetOptAll()
g.Log().Warningf(ctx, "flags:%+v", flags)
if len(flags) == 0 {
g.Log().Fatal(ctx, "工具参数不能为空")
return
}
method, ok := flags["m"]
if !ok {
g.Log().Fatal(ctx, "工具方法不能为空")
return
}
switch method {
case "casbin":
a1, ok := flags["a1"]
if !ok {
g.Log().Fatal(ctx, "casbin参数不能为空")
return
}
if a1 == "clear" {
if err := casbin.Clear(ctx); err != nil {
return err
}
} else if a1 == "refresh" {
casbin.InitEnforcer(ctx)
if err := casbin.Refresh(ctx); err != nil {
return err
}
} else {
g.Log().Fatalf(ctx, "casbin参数无效,a1%+v", a1)
return
}
default:
g.Log().Fatal(ctx, "工具方法不存在")
}
g.Log().Info(ctx, "执行完成!")
return
},
}
)

View File

@@ -0,0 +1,14 @@
// Package consts
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package consts
// 应用类型
const (
AppAdmin = "admin"
AppApi = "api"
AppDefault = "default"
)

View File

@@ -0,0 +1,31 @@
// Package consts
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package consts
// 全局状态码
const (
CodeNil = -1 // No error code specified.
CodeOK = 0 // It is OK.
CodeInternalError = 50 // An error occurred internally.
CodeValidationFailed = 51 // Data validation failed.
CodeDbOperationError = 52 // Database operation error.
CodeInvalidParameter = 53 // The given parameter for current operation is invalid.
CodeMissingParameter = 54 // Parameter for current operation is missing.
CodeInvalidOperation = 55 // The function cannot be used like this.
CodeInvalidConfiguration = 56 // The configuration is invalid for current operation.
CodeMissingConfiguration = 57 // The configuration is missing for current operation.
CodeNotImplemented = 58 // The operation is not implemented yet.
CodeNotSupported = 59 // The operation is not supported yet.
CodeOperationFailed = 60 // I tried, but I cannot give you what you want.
CodeNotAuthorized = 61 // Not Authorized.
CodeSecurityReason = 62 // Security Reason.
CodeServerBusy = 63 // Server is busy, please try again later.
CodeUnknown = 64 // Unknown error.
CodeNotFound = 65 // Resource does not exist.
CodeInvalidRequest = 66 // Invalid request.
CodeBusinessValidationFailed = 300 // Business validation failed.
)

View File

@@ -0,0 +1,15 @@
// Package consts
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package consts
const (
ConfigTypeString = "string"
ConfigTypeInt = "int"
ConfigTypeBool = "bool"
ConfigTypeArray = "array"
ConfigTypeDate = "date"
)

View File

@@ -0,0 +1,12 @@
// Package consts
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package consts
// ContextKey 上下文
const (
ContextKey = "HotGoContext"
)

View File

@@ -0,0 +1,18 @@
// Package consts
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package consts
// 定时任务
const (
CronArgsKey = "args" // 上下文变量名称
CronSplitStr = "," // 变量分割符
CronPolicySame = 1 // 并行策略
CronPolicySingle = 2 // 单例策略
CronPolicyOnce = 3 // 单次策略
CronPolicyTimes = 4 // 多次策略
)

View File

@@ -0,0 +1,13 @@
// Package consts
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package consts
// 碎片
const (
DemoTips = "演示系统已隐藏"
)

View File

@@ -0,0 +1,14 @@
// Package consts
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package consts
// 错误解释
const (
ErrorORM = "sql执行异常"
ErrorNotData = "数据不存在"
ErrorRotaPointer = "指针转换异常"
)

View File

@@ -0,0 +1,15 @@
// Package consts
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package consts
// 开放API
const (
OpenAPITitle = `HotGo`
OpenAPIDescription = `这是一个使用HotGo的简单演示HTTP服务器项目。 `
OpenAPIName = `HotGo`
OpenAPIURL = `https://github.com/bufanyun/hotgo`
)

View File

@@ -0,0 +1,14 @@
// Package consts
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package consts
// 消息队列
const (
QueueName = `queue:`
QueueLogPath = "queue" // 需要在config中配置queue的log
QueueLogTopic = `request_log`
)

View File

@@ -0,0 +1,13 @@
// Package consts
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package consts
// redis
const (
RedisJwtToken = "jwtToken:" // JWT-token
RedisJwtUserBind = "jwtUserBind:" // JWT-用户身份绑定
)

View File

@@ -0,0 +1,17 @@
// Package consts
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package consts
// 状态码
const (
StatusALL int = -1 // 全部状态
StatusEnabled int = 1 // 启用
StatusDisable int = 2 // 禁用
StatusDelete int = 3 // 已删除
)
var StatusMap = []int{StatusALL, StatusEnabled, StatusDisable, StatusDelete}

View File

@@ -0,0 +1,12 @@
// Package consts
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package consts
const (
UploadDriveLocal = "local" // 本地驱动
UploadDriveOss = "oss" // 阿里云oss
)

View File

@@ -0,0 +1,12 @@
// Package consts
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package consts
// VersionApp 应用版本
const (
VersionApp = "1.0.0"
)

View File

@@ -0,0 +1,24 @@
// Package member
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package member
import (
"context"
"github.com/gogf/gf/v2/frame/g"
"hotgo/api/api/member"
)
var (
Member = cMember{}
)
type cMember struct{}
func (c *cMember) GetIdByCode(ctx context.Context, req *member.GetIdByCodeReq) (res *member.GetIdByCodeRes, err error) {
g.RequestFromCtx(ctx).Response.Writeln("Hello World api member!")
return
}

View File

@@ -0,0 +1,25 @@
// Package user
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package user
import (
"context"
"hotgo/api/api/user"
"github.com/gogf/gf/v2/frame/g"
)
var (
Hello = cHello{}
)
type cHello struct{}
func (c *cHello) Hello(ctx context.Context, req *user.HelloReq) (res *user.HelloRes, err error) {
g.RequestFromCtx(ctx).Response.Writeln("Hello World api member!")
return
}

View File

@@ -0,0 +1,142 @@
// Package admin
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package admin
import (
"context"
"github.com/gogf/gf/v2/util/gconv"
"hotgo/api/backend/dept"
"hotgo/internal/model/input/adminin"
"hotgo/internal/service"
)
var (
Dept = cDept{}
)
type cDept struct{}
// NameUnique 名称是否唯一
func (c *cDept) NameUnique(ctx context.Context, req *dept.NameUniqueReq) (*dept.NameUniqueRes, error) {
data, err := service.AdminDept().NameUnique(ctx, adminin.DeptNameUniqueInp{Id: req.Id, Name: req.Name})
if err != nil {
return nil, err
}
var res dept.NameUniqueRes
res.IsUnique = data.IsUnique
return &res, nil
}
// Delete 删除
func (c *cDept) Delete(ctx context.Context, req *dept.DeleteReq) (res *dept.DeleteRes, err error) {
var in adminin.DeptDeleteInp
if err = gconv.Scan(req, &in); err != nil {
return nil, err
}
if err = service.AdminDept().Delete(ctx, in); err != nil {
return nil, err
}
return res, nil
}
// Edit 更新
func (c *cDept) Edit(ctx context.Context, req *dept.EditReq) (res *dept.EditRes, err error) {
var in adminin.DeptEditInp
if err = gconv.Scan(req, &in); err != nil {
return nil, err
}
if err = service.AdminDept().Edit(ctx, in); err != nil {
return nil, err
}
return res, nil
}
// MaxSort 最大排序
func (c *cDept) MaxSort(ctx context.Context, req *dept.MaxSortReq) (*dept.MaxSortRes, error) {
data, err := service.AdminDept().MaxSort(ctx, adminin.DeptMaxSortInp{Id: req.Id})
if err != nil {
return nil, err
}
var res dept.MaxSortRes
res.Sort = data.Sort
return &res, nil
}
// View 获取指定信息
func (c *cDept) View(ctx context.Context, req *dept.ViewReq) (*dept.ViewRes, error) {
data, err := service.AdminDept().View(ctx, adminin.DeptViewInp{Id: req.Id})
if err != nil {
return nil, err
}
var res dept.ViewRes
res.DeptViewModel = data
return &res, nil
}
// List 查看列表
func (c *cDept) List(ctx context.Context, req *dept.ListReq) (*dept.ListRes, error) {
var (
in adminin.DeptListInp
res dept.ListRes
)
if err := gconv.Scan(req, &in); err != nil {
return nil, err
}
data, err := service.AdminDept().List(ctx, in)
if err != nil {
return nil, err
}
_ = gconv.Structs(data, &res)
return &res, nil
}
// ListTree 查看列表树
func (c *cDept) ListTree(ctx context.Context, req *dept.ListTreeReq) (*dept.ListTreeRes, error) {
var (
in adminin.DeptListTreeInp
res dept.ListTreeRes
)
if err := gconv.Scan(req, &in); err != nil {
return nil, err
}
data, err := service.AdminDept().ListTree(ctx, in)
if err != nil {
return nil, err
}
_ = gconv.Structs(data, &res)
return &res, nil
}
// Status 更新部门状态
func (c *cDept) Status(ctx context.Context, req *dept.StatusReq) (res *dept.StatusRes, err error) {
var in adminin.DeptStatusInp
if err = gconv.Scan(req, &in); err != nil {
return nil, err
}
if err = service.AdminDept().Status(ctx, in); err != nil {
return nil, err
}
return res, nil
}

View File

@@ -0,0 +1,289 @@
// Package admin
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package admin
import (
"context"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/util/gconv"
"hotgo/api/backend/member"
"hotgo/internal/library/contexts"
"hotgo/internal/model/input/adminin"
"hotgo/internal/model/input/form"
"hotgo/internal/service"
)
var (
Member = cMember{}
)
type cMember struct{}
// UpdateProfile 修改登录密码
func (c *cMember) UpdateProfile(ctx context.Context, req *member.UpdateProfileReq) (res *member.UpdateProfileRes, err error) {
var in adminin.MemberUpdateProfileInp
if err = gconv.Scan(req, &in); err != nil {
return nil, err
}
if err = service.AdminMember().UpdateProfile(ctx, in); err != nil {
return nil, err
}
return
}
// UpdatePwd 修改登录密码
func (c *cMember) UpdatePwd(ctx context.Context, req *member.UpdatePwdReq) (res *member.UpdatePwdRes, err error) {
memberId := contexts.Get(ctx).User.Id
if memberId <= 0 {
err := gerror.New("获取用户信息失败!")
return nil, err
}
if err = service.AdminMember().
UpdatePwd(ctx, adminin.MemberUpdatePwdInp{Id: memberId, OldPassword: req.OldPassword, NewPassword: req.NewPassword}); err != nil {
return nil, err
}
return
}
// Profile 获取登录用户的基本信息
func (c *cMember) Profile(ctx context.Context, req *member.ProfileReq) (*member.ProfileRes, error) {
var res member.ProfileRes
memberId := contexts.Get(ctx).User.Id
if memberId <= 0 {
err := gerror.New("获取用户信息失败!")
return nil, err
}
// 用户基本信息
memberInfo, err := service.AdminMember().View(ctx, adminin.MemberViewInp{Id: memberId})
if err != nil {
return nil, err
}
res.User = memberInfo
// 所在部门
sysDept, err := service.AdminDept().View(ctx, adminin.DeptViewInp{Id: memberInfo.DeptId})
if err != nil {
return nil, err
}
res.SysDept = sysDept
// 角色列表
sysRoles, err := service.AdminRole().GetMemberList(ctx, memberInfo.Role)
if err != nil {
return nil, err
}
res.SysRoles = sysRoles
// 获取角色名称
roleGroup, err := service.AdminRole().GetName(ctx, memberInfo.Role)
if err != nil {
return nil, err
}
res.RoleGroup = roleGroup
// 获取第一岗位名称
postGroup, err := service.AdminPost().GetMemberByStartName(ctx, memberInfo.Id)
if err != nil {
return nil, err
}
res.PostGroup = postGroup
return &res, nil
}
// ResetPwd 重置密码
func (c *cMember) ResetPwd(ctx context.Context, req *member.ResetPwdReq) (res *member.ResetPwdRes, err error) {
if err = service.AdminMember().
ResetPwd(ctx, adminin.MemberResetPwdInp{Id: req.Id, Password: req.Password}); err != nil {
return nil, err
}
return
}
// EmailUnique 邮箱是否唯一
func (c *cMember) EmailUnique(ctx context.Context, req *member.EmailUniqueReq) (*member.EmailUniqueRes, error) {
data, err := service.AdminMember().EmailUnique(ctx, adminin.MemberEmailUniqueInp{Id: req.Id, Email: req.Email})
if err != nil {
return nil, err
}
var res member.EmailUniqueRes
res.IsUnique = data.IsUnique
return &res, nil
}
// MobileUnique 手机号是否唯一
func (c *cMember) MobileUnique(ctx context.Context, req *member.MobileUniqueReq) (*member.MobileUniqueRes, error) {
data, err := service.AdminMember().MobileUnique(ctx, adminin.MemberMobileUniqueInp{Id: req.Id, Mobile: req.Mobile})
if err != nil {
return nil, err
}
var res member.MobileUniqueRes
res.IsUnique = data.IsUnique
return &res, nil
}
// NameUnique 名称是否唯一
func (c *cMember) NameUnique(ctx context.Context, req *member.NameUniqueReq) (*member.NameUniqueRes, error) {
data, err := service.AdminMember().NameUnique(ctx, adminin.MemberNameUniqueInp{Id: req.Id, Username: req.Username})
if err != nil {
return nil, err
}
var res member.NameUniqueRes
res.IsUnique = data.IsUnique
return &res, nil
}
// Delete 删除
func (c *cMember) Delete(ctx context.Context, req *member.DeleteReq) (res *member.DeleteRes, err error) {
var in adminin.MemberDeleteInp
if err = gconv.Scan(req, &in); err != nil {
return nil, err
}
if err = service.AdminMember().Delete(ctx, in); err != nil {
return nil, err
}
return res, nil
}
// Edit 修改/新增
func (c *cMember) Edit(ctx context.Context, req *member.EditReq) (res *member.EditRes, err error) {
var in adminin.MemberEditInp
if err = gconv.Scan(req, &in); err != nil {
return nil, err
}
if err = service.AdminMember().Edit(ctx, in); err != nil {
return nil, err
}
return res, nil
}
// MaxSort 最大排序
func (c *cMember) MaxSort(ctx context.Context, req *member.MaxSortReq) (*member.MaxSortRes, error) {
data, err := service.AdminMember().MaxSort(ctx, adminin.MemberMaxSortInp{Id: req.Id})
if err != nil {
return nil, err
}
var res member.MaxSortRes
res.Sort = data.Sort
return &res, nil
}
// View 获取指定信息
func (c *cMember) View(ctx context.Context, req *member.ViewReq) (*member.ViewRes, error) {
postsList, _, err := service.AdminPost().List(ctx, adminin.PostListInp{})
if err != nil {
return nil, err
}
roleList, _, err := service.AdminRole().List(ctx, adminin.RoleListInp{})
if err != nil {
return nil, err
}
var res member.ViewRes
res.Posts = postsList
res.Roles = roleList
if req.Id <= 0 {
return &res, err
}
memberInfo, err := service.AdminMember().View(ctx, adminin.MemberViewInp{Id: req.Id})
if err != nil {
return nil, err
}
res.MemberViewModel = memberInfo
res.PostIds, err = service.AdminMemberPost().GetMemberByIds(ctx, memberInfo.Id)
if err != nil {
return nil, err
}
res.RoleIds = []int64{memberInfo.Role}
res.DeptName, err = service.AdminDept().GetName(ctx, memberInfo.DeptId)
if err != nil {
return nil, err
}
return &res, nil
}
// List 查看列表
func (c *cMember) List(ctx context.Context, req *member.ListReq) (*member.ListRes, error) {
var (
in adminin.MemberListInp
res member.ListRes
)
if err := gconv.Scan(req, &in); err != nil {
return nil, err
}
list, totalCount, err := service.AdminMember().List(ctx, in)
if err != nil {
return nil, err
}
res.List = list
res.PageCount = form.CalPageCount(totalCount, req.PerPage)
res.Page = req.Page
res.PerPage = req.PerPage
return &res, nil
}
// Info 登录用户信息
func (c *cMember) Info(ctx context.Context, req *member.InfoReq) (res *member.InfoRes, err error) {
model, err := service.AdminMember().LoginMemberInfo(ctx, req)
if err != nil {
return nil, err
}
if err = gconv.Scan(model, &res); err != nil {
return nil, err
}
return
}
// Status 更新状态
func (c *cMember) Status(ctx context.Context, req *member.StatusReq) (res *member.StatusRes, err error) {
var in adminin.MemberStatusInp
if err = gconv.Scan(req, &in); err != nil {
return nil, err
}
if err = service.AdminMember().Status(ctx, in); err != nil {
return nil, err
}
return res, nil
}

View File

@@ -0,0 +1,120 @@
// Package admin
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package admin
import (
"context"
"github.com/gogf/gf/v2/util/gconv"
"hotgo/api/backend/menu"
"hotgo/internal/model/input/adminin"
"hotgo/internal/service"
)
// Menu 菜单
var (
Menu = cMenu{}
)
type cMenu struct{}
// RoleList 查询角色菜单列表
func (c *cMenu) RoleList(ctx context.Context, req *menu.RoleListReq) (*menu.RoleListRes, error) {
var in adminin.MenuRoleListInp
if err := gconv.Scan(req, &in); err != nil {
return nil, err
}
data, err := service.AdminMenu().RoleList(ctx, in)
if err != nil {
return nil, err
}
var res menu.RoleListRes
res.CheckedKeys = data.CheckedKeys
res.Menus = data.Menus
return &res, nil
}
// SearchList 查询菜单列表
func (c *cMenu) SearchList(ctx context.Context, req *menu.SearchListReq) (res *menu.SearchListRes, err error) {
res, err = service.AdminMenu().SearchList(ctx, req)
if err != nil {
return nil, err
}
return res, nil
}
// MaxSort 最大排序
func (c *cMenu) MaxSort(ctx context.Context, req *menu.MaxSortReq) (res *menu.MaxSortRes, err error) {
res, err = service.AdminMenu().MaxSort(ctx, req)
if err != nil {
return nil, err
}
return res, nil
}
// NameUnique 菜单名称是否唯一
func (c *cMenu) NameUnique(ctx context.Context, req *menu.NameUniqueReq) (res *menu.NameUniqueRes, err error) {
res, err = service.AdminMenu().NameUnique(ctx, req)
if err != nil {
return nil, err
}
return res, nil
}
// CodeUnique 菜单编码是否唯一
func (c *cMenu) CodeUnique(ctx context.Context, req *menu.CodeUniqueReq) (res *menu.CodeUniqueRes, err error) {
res, err = service.AdminMenu().CodeUnique(ctx, req)
if err != nil {
return nil, err
}
return res, nil
}
// Delete 删除
func (c *cMenu) Delete(ctx context.Context, req *menu.DeleteReq) (res *menu.DeleteRes, err error) {
if err = service.AdminMenu().Delete(ctx, req); err != nil {
return nil, err
}
return res, nil
}
// Edit 更新
func (c *cMenu) Edit(ctx context.Context, req *menu.EditReq) (res *menu.EditRes, err error) {
if err = service.AdminMenu().Edit(ctx, req); err != nil {
return nil, err
}
return res, nil
}
// View 获取信息
func (c *cMenu) View(ctx context.Context, req *menu.ViewReq) (res *menu.ViewRes, err error) {
res, err = service.AdminMenu().View(ctx, req)
if err != nil {
return nil, err
}
return res, nil
}
// List 获取列表
func (c *cMenu) List(ctx context.Context, req *menu.ListReq) (res menu.ListRes, err error) {
res.List, err = service.AdminMenu().List(ctx, req)
if err != nil {
return res, err
}
return res, nil
}

View File

@@ -0,0 +1,110 @@
// Package admin
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package admin
import (
"context"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/grpool"
"hotgo/api/backend/monitor"
"hotgo/internal/consts"
"hotgo/internal/model/input/form"
"hotgo/internal/websocket"
"hotgo/utility/useragent"
"sort"
)
// Monitor 监控
var Monitor = cMonitor{
wsManager: websocket.Manager(),
}
type cMonitor struct {
wsManager *websocket.ClientManager
}
// Offline 下线用户
func (c *cMonitor) Offline(ctx context.Context, req *monitor.OfflineReq) (res *monitor.OfflineRes, err error) {
client := c.wsManager.GetClient(req.Id)
if client == nil {
err = gerror.New("客户端已离线")
return
}
err = grpool.AddWithRecover(ctx, func(ctx context.Context) {
websocket.SendSuccess(client, "kick")
websocket.Close(client)
})
if err != nil {
return nil, err
}
return res, nil
}
// View 获取指定信息
func (c *cMonitor) View(ctx context.Context, req *monitor.OnlineViewReq) (*monitor.OnlineViewRes, error) {
var res monitor.OnlineViewRes
// ...
return &res, nil
}
// OnlineList 获取在线列表
func (c *cMonitor) OnlineList(ctx context.Context, req *monitor.OnlineListReq) (*monitor.OnlineListRes, error) {
var (
res monitor.OnlineListRes
clients []*monitor.OnlineModel
i int
)
if c.wsManager.GetClientsLen() == 0 {
return &res, nil
}
for c, _ := range c.wsManager.GetClients() {
if c.SendClose || c.User == nil {
continue
}
if req.UserId > 0 && req.UserId != c.User.Id {
continue
}
clients = append(clients, &monitor.OnlineModel{
ID: c.ID,
Addr: c.Addr,
Os: useragent.GetOs(c.UserAgent),
Browser: useragent.GetBrowser(c.UserAgent),
FirstTime: c.FirstTime,
HeartbeatTime: c.HeartbeatTime,
App: c.User.App,
UserId: c.User.Id,
Username: c.User.Username,
Avatar: c.User.Avatar,
ExpTime: c.User.Exp,
})
}
res.PageCount = form.CalPageCount(len(clients), req.PerPage)
res.Page = req.Page
res.PerPage = req.PerPage
sort.Sort(monitor.OnlineModels(clients))
isDemo, _ := g.Cfg().Get(ctx, "hotgo.isDemo", false)
_, perPage, offset := form.CalPage(ctx, req.Page, req.PerPage)
for k, v := range clients {
if k >= offset && i <= perPage {
i++
if isDemo.Bool() {
v.Addr = consts.DemoTips
}
res.List = append(res.List, v)
}
}
return &res, nil
}

View File

@@ -0,0 +1,113 @@
// Package admin
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package admin
import (
"context"
"github.com/gogf/gf/v2/util/gconv"
"hotgo/api/backend/notice"
"hotgo/internal/model/input/adminin"
"hotgo/internal/model/input/form"
"hotgo/internal/service"
)
var (
Notice = cNotice{}
)
type cNotice struct{}
// Delete 删除
func (c *cNotice) Delete(ctx context.Context, req *notice.DeleteReq) (res *notice.DeleteRes, err error) {
var in adminin.NoticeDeleteInp
if err = gconv.Scan(req, &in); err != nil {
return nil, err
}
if err = service.AdminNotice().Delete(ctx, in); err != nil {
return nil, err
}
return res, nil
}
// Edit 更新
func (c *cNotice) Edit(ctx context.Context, req *notice.EditReq) (res *notice.EditRes, err error) {
var in adminin.NoticeEditInp
if err = gconv.Scan(req, &in); err != nil {
return nil, err
}
if err = service.AdminNotice().Edit(ctx, in); err != nil {
return nil, err
}
return res, nil
}
// MaxSort 最大排序
func (c *cNotice) MaxSort(ctx context.Context, req *notice.MaxSortReq) (*notice.MaxSortRes, error) {
data, err := service.AdminNotice().MaxSort(ctx, adminin.NoticeMaxSortInp{Id: req.Id})
if err != nil {
return nil, err
}
var res notice.MaxSortRes
res.Sort = data.Sort
return &res, nil
}
// View 获取指定信息
func (c *cNotice) View(ctx context.Context, req *notice.ViewReq) (*notice.ViewRes, error) {
data, err := service.AdminNotice().View(ctx, adminin.NoticeViewInp{Id: req.Id})
if err != nil {
return nil, err
}
var res notice.ViewRes
res.NoticeViewModel = data
return &res, nil
}
// List 查看列表
func (c *cNotice) List(ctx context.Context, req *notice.ListReq) (*notice.ListRes, error) {
var (
in adminin.NoticeListInp
res notice.ListRes
)
if err := gconv.Scan(req, &in); err != nil {
return nil, err
}
list, totalCount, err := service.AdminNotice().List(ctx, in)
if err != nil {
return nil, err
}
res.List = list
res.PageCount = form.CalPageCount(totalCount, req.PerPage)
res.Page = req.Page
res.PerPage = req.PerPage
return &res, nil
}
// Status 更新部门状态
func (c *cNotice) Status(ctx context.Context, req *notice.StatusReq) (res *notice.StatusRes, err error) {
var in adminin.NoticeStatusInp
if err = gconv.Scan(req, &in); err != nil {
return nil, err
}
if err = service.AdminNotice().Status(ctx, in); err != nil {
return nil, err
}
return res, nil
}

View File

@@ -0,0 +1,140 @@
// Package admin
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package admin
import (
"context"
"github.com/gogf/gf/v2/util/gconv"
"hotgo/api/backend/post"
"hotgo/internal/model/input/adminin"
"hotgo/internal/model/input/form"
"hotgo/internal/service"
)
// Post 岗位
var Post = cPost{}
type cPost struct{}
// Delete 删除
func (c *cPost) Delete(ctx context.Context, req *post.DeleteReq) (res *post.DeleteRes, err error) {
var in adminin.PostDeleteInp
if err = gconv.Scan(req, &in); err != nil {
return nil, err
}
if err = service.AdminPost().Delete(ctx, in); err != nil {
return nil, err
}
return res, nil
}
// Edit 修改/新增
func (c *cPost) Edit(ctx context.Context, req *post.EditReq) (res *post.EditRes, err error) {
var in adminin.PostEditInp
if err = gconv.Scan(req, &in); err != nil {
return nil, err
}
if err = service.AdminPost().Edit(ctx, in); err != nil {
return nil, err
}
return res, nil
}
// MaxSort 最大排序
func (c *cPost) MaxSort(ctx context.Context, req *post.MaxSortReq) (*post.MaxSortRes, error) {
data, err := service.AdminPost().MaxSort(ctx, adminin.PostMaxSortInp{Id: req.Id})
if err != nil {
return nil, err
}
var res post.MaxSortRes
res.Sort = data.Sort
return &res, nil
}
// NameUnique 名称是否唯一
func (c *cPost) NameUnique(ctx context.Context, req *post.NameUniqueReq) (*post.NameUniqueRes, error) {
data, err := service.AdminPost().NameUnique(ctx, adminin.PostNameUniqueInp{Id: req.Id, Name: req.Name})
if err != nil {
return nil, err
}
var res post.NameUniqueRes
res.IsUnique = data.IsUnique
return &res, nil
}
// CodeUnique 编码是否唯一
func (c *cPost) CodeUnique(ctx context.Context, req *post.CodeUniqueReq) (*post.CodeUniqueRes, error) {
data, err := service.AdminPost().CodeUnique(ctx, adminin.PostCodeUniqueInp{Id: req.Id, Code: req.Code})
if err != nil {
return nil, err
}
var res post.CodeUniqueRes
res.IsUnique = data.IsUnique
return &res, nil
}
// View 获取指定信息
func (c *cPost) View(ctx context.Context, req *post.ViewReq) (*post.ViewRes, error) {
data, err := service.AdminPost().View(ctx, adminin.PostViewInp{Id: req.Id})
if err != nil {
return nil, err
}
var res post.ViewRes
res.PostViewModel = data
return &res, nil
}
// List 获取列表
func (c *cPost) List(ctx context.Context, req *post.ListReq) (*post.ListRes, error) {
var in adminin.PostListInp
if err := gconv.Scan(req, &in); err != nil {
return nil, err
}
//adminin.PostListInp{
// Page: req.Page,
// PerPage: req.PerPage,
// Name: req.Name,
// Code: req.Code,
// Status: req.Status,
//}
list, totalCount, err := service.AdminPost().List(ctx, in)
if err != nil {
return nil, err
}
var res post.ListRes
res.List = list
res.PageCount = form.CalPageCount(totalCount, req.PerPage)
res.Page = req.Page
res.PerPage = req.PerPage
return &res, nil
}
// Status 更新状态
func (c *cPost) Status(ctx context.Context, req *post.StatusReq) (res *post.StatusRes, err error) {
var in adminin.PostStatusInp
if err = gconv.Scan(req, &in); err != nil {
return nil, err
}
if err = service.AdminPost().Status(ctx, in); err != nil {
return nil, err
}
return res, nil
}

View File

@@ -0,0 +1,117 @@
// Package admin
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package admin
import (
"context"
"github.com/gogf/gf/v2/util/gconv"
"hotgo/api/backend/role"
"hotgo/internal/library/contexts"
"hotgo/internal/model/input/adminin"
"hotgo/internal/model/input/form"
"hotgo/internal/service"
)
var (
Role = cRole{}
)
type cRole struct{}
// RoleMemberList 获取角色下的会员列表
func (c *cRole) RoleMemberList(ctx context.Context, req *role.MemberListReq) (*role.MemberListRes, error) {
var in adminin.RoleMemberListInp
if err := gconv.Scan(req, &in); err != nil {
return nil, err
}
list, totalCount, err := service.AdminMember().RoleMemberList(ctx, in)
if err != nil {
return nil, err
}
var res role.MemberListRes
res.List = list
res.PageCount = form.CalPageCount(totalCount, req.PerPage)
res.PerPage = req.Page
res.PerPage = req.PerPage
return &res, nil
}
// List 获取列表
func (c *cRole) List(ctx context.Context, req *role.ListReq) (*role.ListRes, error) {
list, totalCount, err := service.AdminRole().List(ctx, adminin.RoleListInp{
Page: req.Page,
PerPage: req.PerPage,
})
if err != nil {
return nil, err
}
var res role.ListRes
res.List = list
res.PageCount = form.CalPageCount(totalCount, req.PerPage)
res.PerPage = req.Page
res.PerPage = req.PerPage
return &res, nil
}
// Edit 修改角色
func (c *cRole) Edit(ctx context.Context, req *role.EditReq) (res *role.EditRes, err error) {
err = service.AdminRole().Edit(ctx, req)
if err != nil {
return nil, err
}
return res, nil
}
// Delete 删除
func (c *cRole) Delete(ctx context.Context, req *role.DeleteReq) (res *role.DeleteRes, err error) {
if err = service.AdminRole().Delete(ctx, req); err != nil {
return nil, err
}
return res, nil
}
// Dynamic 动态路由
func (c *cRole) Dynamic(ctx context.Context, req *role.DynamicReq) (res role.DynamicRes, err error) {
res, err = service.AdminMenu().GetMenuList(ctx, contexts.GetUserId(ctx))
if err != nil {
return res, err
}
return res, nil
}
// GetPermissions 获取指定角色权限
func (c *cRole) GetPermissions(ctx context.Context, req *role.GetPermissionsReq) (res *role.GetPermissionsRes, err error) {
MenuIds, err := service.AdminRole().GetPermissions(ctx, req)
if err != nil {
return nil, err
}
res = &role.GetPermissionsRes{
MenuIds: []int64{},
}
if MenuIds != nil {
res.MenuIds = MenuIds
}
return res, nil
}
// UpdatePermissions 修改角色菜单权限
func (c *cRole) UpdatePermissions(ctx context.Context, req *role.UpdatePermissionsReq) (res *role.UpdatePermissionsRes, err error) {
err = service.AdminRole().UpdatePermissions(ctx, req)
if err != nil {
return nil, err
}
return res, nil
}

View File

@@ -0,0 +1,42 @@
// Package common
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package common
import (
"context"
"hotgo/api/backend/common"
)
var Console = cConsole{}
type cConsole struct{}
// Stat 综合数据统计
func (c *cConsole) Stat(ctx context.Context, req *common.ConsoleStatReq) (res *common.ConsoleStatRes, err error) {
res = new(common.ConsoleStatRes)
res.Visits.DayVisits = 12010
res.Visits.Rise = 13501
res.Visits.Decline = 10502
res.Visits.Amount = 10403
res.Saleroom.WeekSaleroom = 20501
res.Saleroom.Amount = 21002
res.Saleroom.Degree = 83.66
res.OrderLarge.WeekLarge = 39901
res.OrderLarge.Rise = 31012
res.OrderLarge.Decline = 30603
res.OrderLarge.Amount = 36084
res.Volume.WeekLarge = 40021
res.Volume.Rise = 40202
res.Volume.Decline = 45003
res.Volume.Amount = 49004
return
}

View File

@@ -0,0 +1,32 @@
// Package common
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package common
import (
"context"
"hotgo/api/backend/common"
"hotgo/internal/library/ems"
"hotgo/internal/service"
)
var Ems = new(cEms)
type cEms struct{}
// SendTest 发送测试邮件
func (c *cEms) SendTest(ctx context.Context, req *common.SendTestEmailReq) (res *common.SendTestEmailRes, err error) {
conf, err := service.SysConfig().GetSmtp(ctx)
if err != nil {
return
}
if err = ems.SendTestMail(conf, req.To); err != nil {
return nil, err
}
return
}

View File

@@ -0,0 +1,101 @@
// Package common
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package common
import (
"context"
"github.com/gogf/gf/v2/crypto/gmd5"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
"github.com/gogf/gf/v2/util/gconv"
"hotgo/api/backend/common"
"hotgo/internal/consts"
"hotgo/internal/library/cache"
"hotgo/internal/library/captcha"
"hotgo/internal/library/jwt"
"hotgo/internal/model/input/adminin"
"hotgo/internal/service"
)
var Site = cSite{}
type cSite struct{}
// Ping ping
func (c *cSite) Ping(ctx context.Context, req *common.SitePingReq) (res *common.SitePingRes, err error) {
return
}
// Config 获取配置
func (c *cSite) Config(ctx context.Context, req *common.SiteConfigReq) (res *common.SiteConfigRes, err error) {
wsAddr, _ := g.Cfg().Get(ctx, "hotgo.wsAddr", "ws://127.0.0.1:8000/ws")
g.Log().Warningf(ctx, "wsAddr:%+v", wsAddr.String())
res = &common.SiteConfigRes{
Version: consts.VersionApp,
WsAddr: wsAddr.String(),
}
return
}
// Captcha 登录验证码
func (c *cSite) Captcha(ctx context.Context, req *common.LoginCaptchaReq) (res *common.LoginCaptchaRes, err error) {
// 获取生成的验证码图片
Cid, Base64 := captcha.GetVerifyImgString(ctx)
res = &common.LoginCaptchaRes{Cid: Cid, Base64: Base64}
return
}
// Login 提交登录
func (c *cSite) Login(ctx context.Context, req *common.LoginReq) (res *common.LoginRes, err error) {
//// 校验 验证码
//if !captcha.VerifyString(req.Cid, req.Code) {
// err = gerror.New("验证码错误")
// return
//}
//
var in adminin.MemberLoginInp
if err = gconv.Scan(req, &in); err != nil {
return nil, err
}
model, err := service.AdminMember().Login(ctx, in)
if err != nil {
return nil, err
}
if err = gconv.Scan(model, &res); err != nil {
return nil, err
}
return
}
// Logout 注销登录
func (c *cSite) Logout(ctx context.Context, req *common.LoginLogoutReq) (res *common.LoginLogoutRes, err error) {
var authorization = jwt.GetAuthorization(ghttp.RequestFromCtx(ctx))
// 获取jwtToken
jwtToken := consts.RedisJwtToken + gmd5.MustEncryptString(authorization)
if len(jwtToken) == 0 {
err = gerror.New("当前用户未登录!")
return res, err
}
// 删除登录token
ca := cache.New()
_, err = ca.Remove(ctx, jwtToken)
if err != nil {
return res, err
}
return
}

View File

@@ -0,0 +1,36 @@
// Package common
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package common
import (
"context"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g"
"hotgo/api/backend/common"
"hotgo/internal/service"
)
var Upload = new(cUpload)
type cUpload struct{}
// UploadImage 上传图片
func (c *cUpload) UploadImage(ctx context.Context, req *common.UploadImageReq) (res common.UploadImageRes, err error) {
r := g.RequestFromCtx(ctx)
file := r.GetUploadFile("file")
if file == nil {
err = gerror.New("没有找到上传的文件")
return
}
res, err = service.CommonUpload().UploadImage(ctx, file)
if err != nil {
return
}
return
}

View File

@@ -0,0 +1,113 @@
// Package sys
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package sys
import (
"context"
"github.com/gogf/gf/v2/util/gconv"
"hotgo/api/backend/attachment"
"hotgo/internal/model/input/form"
"hotgo/internal/model/input/sysin"
"hotgo/internal/service"
)
var (
Attachment = cAttachment{}
)
type cAttachment struct{}
// Delete 删除
func (c *cAttachment) Delete(ctx context.Context, req *attachment.DeleteReq) (res *attachment.DeleteRes, err error) {
var in sysin.AttachmentDeleteInp
if err = gconv.Scan(req, &in); err != nil {
return nil, err
}
if err = service.SysAttachment().Delete(ctx, in); err != nil {
return nil, err
}
return res, nil
}
// Edit 更新
func (c *cAttachment) Edit(ctx context.Context, req *attachment.EditReq) (res *attachment.EditRes, err error) {
var in sysin.AttachmentEditInp
if err = gconv.Scan(req, &in); err != nil {
return nil, err
}
if err = service.SysAttachment().Edit(ctx, in); err != nil {
return nil, err
}
return res, nil
}
// MaxSort 最大排序
func (c *cAttachment) MaxSort(ctx context.Context, req *attachment.MaxSortReq) (*attachment.MaxSortRes, error) {
data, err := service.SysAttachment().MaxSort(ctx, sysin.AttachmentMaxSortInp{Id: req.Id})
if err != nil {
return nil, err
}
var res attachment.MaxSortRes
res.Sort = data.Sort
return &res, nil
}
// View 获取指定信息
func (c *cAttachment) View(ctx context.Context, req *attachment.ViewReq) (*attachment.ViewRes, error) {
data, err := service.SysAttachment().View(ctx, sysin.AttachmentViewInp{Id: req.Id})
if err != nil {
return nil, err
}
var res attachment.ViewRes
res.AttachmentViewModel = data
return &res, nil
}
// List 查看列表
func (c *cAttachment) List(ctx context.Context, req *attachment.ListReq) (*attachment.ListRes, error) {
var (
in sysin.AttachmentListInp
res attachment.ListRes
)
if err := gconv.Scan(req, &in); err != nil {
return nil, err
}
list, totalCount, err := service.SysAttachment().List(ctx, in)
if err != nil {
return nil, err
}
res.List = list
res.PageCount = form.CalPageCount(totalCount, req.PerPage)
res.Page = req.Page
res.PerPage = req.PerPage
return &res, nil
}
// Status 更新部门状态
func (c *cAttachment) Status(ctx context.Context, req *attachment.StatusReq) (res *attachment.StatusRes, err error) {
var in sysin.AttachmentStatusInp
if err = gconv.Scan(req, &in); err != nil {
return nil, err
}
if err = service.SysAttachment().Status(ctx, in); err != nil {
return nil, err
}
return res, nil
}

View File

@@ -0,0 +1,113 @@
// Package sys
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package sys
import (
"context"
"github.com/gogf/gf/v2/util/gconv"
"hotgo/api/backend/blacklist"
"hotgo/internal/model/input/form"
"hotgo/internal/model/input/sysin"
"hotgo/internal/service"
)
var (
Blacklist = cBlacklist{}
)
type cBlacklist struct{}
// Delete 删除
func (c *cBlacklist) Delete(ctx context.Context, req *blacklist.DeleteReq) (res *blacklist.DeleteRes, err error) {
var in sysin.BlacklistDeleteInp
if err = gconv.Scan(req, &in); err != nil {
return nil, err
}
if err = service.SysBlacklist().Delete(ctx, in); err != nil {
return nil, err
}
return res, nil
}
// Edit 更新
func (c *cBlacklist) Edit(ctx context.Context, req *blacklist.EditReq) (res *blacklist.EditRes, err error) {
var in sysin.BlacklistEditInp
if err = gconv.Scan(req, &in); err != nil {
return nil, err
}
if err = service.SysBlacklist().Edit(ctx, in); err != nil {
return nil, err
}
return res, nil
}
// MaxSort 最大排序
func (c *cBlacklist) MaxSort(ctx context.Context, req *blacklist.MaxSortReq) (*blacklist.MaxSortRes, error) {
data, err := service.SysBlacklist().MaxSort(ctx, sysin.BlacklistMaxSortInp{Id: req.Id})
if err != nil {
return nil, err
}
var res blacklist.MaxSortRes
res.Sort = data.Sort
return &res, nil
}
// View 获取指定信息
func (c *cBlacklist) View(ctx context.Context, req *blacklist.ViewReq) (*blacklist.ViewRes, error) {
data, err := service.SysBlacklist().View(ctx, sysin.BlacklistViewInp{Id: req.Id})
if err != nil {
return nil, err
}
var res blacklist.ViewRes
res.BlacklistViewModel = data
return &res, nil
}
// List 查看列表
func (c *cBlacklist) List(ctx context.Context, req *blacklist.ListReq) (*blacklist.ListRes, error) {
var (
in sysin.BlacklistListInp
res blacklist.ListRes
)
if err := gconv.Scan(req, &in); err != nil {
return nil, err
}
list, totalCount, err := service.SysBlacklist().List(ctx, in)
if err != nil {
return nil, err
}
res.List = list
res.PageCount = form.CalPageCount(totalCount, req.PerPage)
res.Page = req.Page
res.PerPage = req.PerPage
return &res, nil
}
// Status 更新部门状态
func (c *cBlacklist) Status(ctx context.Context, req *blacklist.StatusReq) (res *blacklist.StatusRes, err error) {
var in sysin.BlacklistStatusInp
if err = gconv.Scan(req, &in); err != nil {
return nil, err
}
if err = service.SysBlacklist().Status(ctx, in); err != nil {
return nil, err
}
return res, nil
}

View File

@@ -0,0 +1,57 @@
// Package sys
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package sys
import (
"context"
"github.com/gogf/gf/v2/util/gconv"
"hotgo/api/backend/config"
"hotgo/internal/model/input/sysin"
"hotgo/internal/service"
)
var (
Config = cConfig{}
)
type cConfig struct{}
// GetConfig 获取指定分组的配置
func (c *cConfig) GetConfig(ctx context.Context, req *config.GetReq) (*config.GetRes, error) {
var (
in sysin.GetConfigInp
res config.GetRes
err error
)
if err = gconv.Scan(req, &in); err != nil {
return nil, err
}
res.GetConfigModel, err = service.SysConfig().GetConfigByGroup(ctx, in)
if err != nil {
return nil, err
}
return &res, nil
}
// UpdateConfig 更新指定分组的配置
func (c *cConfig) UpdateConfig(ctx context.Context, req *config.UpdateReq) (*config.UpdateRes, error) {
var (
in sysin.UpdateConfigInp
res config.UpdateRes
err error
)
if err = gconv.Scan(req, &in); err != nil {
return nil, err
}
if err = service.SysConfig().UpdateConfigByGroup(ctx, in); err != nil {
return nil, err
}
return &res, nil
}

View File

@@ -0,0 +1,113 @@
// Package sys
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package sys
import (
"context"
"github.com/gogf/gf/v2/util/gconv"
"hotgo/api/backend/cron"
"hotgo/internal/model/input/form"
"hotgo/internal/model/input/sysin"
"hotgo/internal/service"
)
var (
Cron = cCron{}
)
type cCron struct{}
// Delete 删除
func (c *cCron) Delete(ctx context.Context, req *cron.DeleteReq) (res *cron.DeleteRes, err error) {
var in sysin.CronDeleteInp
if err = gconv.Scan(req, &in); err != nil {
return nil, err
}
if err = service.SysCron().Delete(ctx, in); err != nil {
return nil, err
}
return res, nil
}
// Edit 更新
func (c *cCron) Edit(ctx context.Context, req *cron.EditReq) (res *cron.EditRes, err error) {
var in sysin.CronEditInp
if err = gconv.Scan(req, &in); err != nil {
return nil, err
}
if err = service.SysCron().Edit(ctx, in); err != nil {
return nil, err
}
return res, nil
}
// MaxSort 最大排序
func (c *cCron) MaxSort(ctx context.Context, req *cron.MaxSortReq) (*cron.MaxSortRes, error) {
data, err := service.SysCron().MaxSort(ctx, sysin.CronMaxSortInp{Id: req.Id})
if err != nil {
return nil, err
}
var res cron.MaxSortRes
res.Sort = data.Sort
return &res, nil
}
// View 获取指定信息
func (c *cCron) View(ctx context.Context, req *cron.ViewReq) (*cron.ViewRes, error) {
data, err := service.SysCron().View(ctx, sysin.CronViewInp{Id: req.Id})
if err != nil {
return nil, err
}
var res cron.ViewRes
res.CronViewModel = data
return &res, nil
}
// List 查看列表
func (c *cCron) List(ctx context.Context, req *cron.ListReq) (*cron.ListRes, error) {
var (
in sysin.CronListInp
res cron.ListRes
)
if err := gconv.Scan(req, &in); err != nil {
return nil, err
}
list, totalCount, err := service.SysCron().List(ctx, in)
if err != nil {
return nil, err
}
res.List = list
res.PageCount = form.CalPageCount(totalCount, req.PerPage)
res.Page = req.Page
res.PerPage = req.PerPage
return &res, nil
}
// Status 更新部门状态
func (c *cCron) Status(ctx context.Context, req *cron.StatusReq) (res *cron.StatusRes, err error) {
var in sysin.CronStatusInp
if err = gconv.Scan(req, &in); err != nil {
return nil, err
}
if err = service.SysCron().Status(ctx, in); err != nil {
return nil, err
}
return res, nil
}

View File

@@ -0,0 +1,124 @@
// Package sys
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package sys
import (
"context"
"github.com/gogf/gf/v2/util/gconv"
"hotgo/api/backend/cron"
"hotgo/internal/model/input/form"
"hotgo/internal/model/input/sysin"
"hotgo/internal/service"
)
var (
CronGroup = cCronGroup{}
)
type cCronGroup struct{}
// Delete 删除
func (c *cCronGroup) Delete(ctx context.Context, req *cron.GroupDeleteReq) (res *cron.GroupDeleteRes, err error) {
var in sysin.CronGroupDeleteInp
if err = gconv.Scan(req, &in); err != nil {
return nil, err
}
if err = service.SysCronGroup().Delete(ctx, in); err != nil {
return nil, err
}
return res, nil
}
// Edit 更新
func (c *cCronGroup) Edit(ctx context.Context, req *cron.GroupEditReq) (res *cron.GroupEditRes, err error) {
var in sysin.CronGroupEditInp
if err = gconv.Scan(req, &in); err != nil {
return nil, err
}
if err = service.SysCronGroup().Edit(ctx, in); err != nil {
return nil, err
}
return res, nil
}
// MaxSort 最大排序
func (c *cCronGroup) MaxSort(ctx context.Context, req *cron.GroupMaxSortReq) (*cron.GroupMaxSortRes, error) {
data, err := service.SysCronGroup().MaxSort(ctx, sysin.CronGroupMaxSortInp{Id: req.Id})
if err != nil {
return nil, err
}
var res cron.GroupMaxSortRes
res.Sort = data.Sort
return &res, nil
}
// View 获取指定信息
func (c *cCronGroup) View(ctx context.Context, req *cron.GroupViewReq) (*cron.GroupViewRes, error) {
data, err := service.SysCronGroup().View(ctx, sysin.CronGroupViewInp{Id: req.Id})
if err != nil {
return nil, err
}
var res cron.GroupViewRes
res.CronGroupViewModel = data
return &res, nil
}
// List 查看列表
func (c *cCronGroup) List(ctx context.Context, req *cron.GroupListReq) (*cron.GroupListRes, error) {
var (
in sysin.CronGroupListInp
res cron.GroupListRes
)
if err := gconv.Scan(req, &in); err != nil {
return nil, err
}
list, totalCount, err := service.SysCronGroup().List(ctx, in)
if err != nil {
return nil, err
}
res.List = list
res.PageCount = form.CalPageCount(totalCount, req.PerPage)
res.Page = req.Page
res.PerPage = req.PerPage
return &res, nil
}
// Status 更新部门状态
func (c *cCronGroup) Status(ctx context.Context, req *cron.GroupStatusReq) (res *cron.GroupStatusRes, err error) {
var in sysin.CronGroupStatusInp
if err = gconv.Scan(req, &in); err != nil {
return nil, err
}
if err = service.SysCronGroup().Status(ctx, in); err != nil {
return nil, err
}
return res, nil
}
// Select 选项
func (c *cCronGroup) Select(ctx context.Context, req *cron.GroupSelectReq) (res *cron.GroupSelectRes, err error) {
list, err := service.SysCronGroup().Select(ctx, sysin.CronGroupSelectInp{})
if err != nil {
return nil, err
}
res = (*cron.GroupSelectRes)(&list)
return res, nil
}

View File

@@ -0,0 +1,73 @@
// Package sys
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package sys
import (
"context"
"github.com/gogf/gf/v2/util/gconv"
"hotgo/api/backend/dict"
"hotgo/internal/model/input/form"
"hotgo/internal/model/input/sysin"
"hotgo/internal/service"
)
var (
DictData = cDictData{}
)
type cDictData struct{}
// Delete 删除
func (c *cDictData) Delete(ctx context.Context, req *dict.DataDeleteReq) (res *dict.DataDeleteRes, err error) {
var in sysin.DictDataDeleteInp
if err = gconv.Scan(req, &in); err != nil {
return nil, err
}
if err = service.SysDictData().Delete(ctx, in); err != nil {
return nil, err
}
return res, nil
}
// Edit 更新
func (c *cDictData) Edit(ctx context.Context, req *dict.DataEditReq) (res *dict.DataEditRes, err error) {
var in sysin.DictDataEditInp
if err = gconv.Scan(req, &in); err != nil {
return nil, err
}
if err = service.SysDictData().Edit(ctx, in); err != nil {
return nil, err
}
return res, nil
}
// List 查看列表
func (c *cDictData) List(ctx context.Context, req *dict.DataListReq) (*dict.DataListRes, error) {
var (
in sysin.DictDataListInp
res dict.DataListRes
)
if err := gconv.Scan(req, &in); err != nil {
return nil, err
}
list, totalCount, err := service.SysDictData().List(ctx, in)
if err != nil {
return nil, err
}
res.List = list
res.PageCount = form.CalPageCount(totalCount, req.PerPage)
res.Page = req.Page
res.PerPage = req.PerPage
return &res, nil
}

View File

@@ -0,0 +1,72 @@
// Package sys
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package sys
import (
"context"
"github.com/gogf/gf/v2/util/gconv"
"hotgo/api/backend/dict"
"hotgo/internal/model/input/sysin"
"hotgo/internal/service"
)
var (
DictType = cDictType{}
)
type cDictType struct{}
// Tree 树
func (c *cDictType) Tree(ctx context.Context, req *dict.TypeTreeReq) (*dict.TypeTreeRes, error) {
var (
res dict.TypeTreeRes
err error
)
res.List, err = service.SysDictType().Tree(ctx)
if err != nil {
return nil, err
}
return &res, nil
}
// Delete 删除
func (c *cDictType) Delete(ctx context.Context, req *dict.TypeDeleteReq) (res *dict.TypeDeleteRes, err error) {
var in sysin.DictTypeDeleteInp
if err = gconv.Scan(req, &in); err != nil {
return nil, err
}
if err = service.SysDictType().Delete(ctx, in); err != nil {
return nil, err
}
return res, nil
}
// Edit 更新
func (c *cDictType) Edit(ctx context.Context, req *dict.TypeEditReq) (res *dict.TypeEditRes, err error) {
var in sysin.DictTypeEditInp
if err = gconv.Scan(req, &in); err != nil {
return nil, err
}
if err = service.SysDictType().Edit(ctx, in); err != nil {
return nil, err
}
return res, nil
}
// Select 选项
func (c *cDictType) Select(ctx context.Context, req *dict.TypeSelectReq) (res *dict.TypeSelectRes, err error) {
list, err := service.SysDictType().Select(ctx, sysin.DictTypeSelectInp{})
if err != nil {
return nil, err
}
res = (*dict.TypeSelectRes)(&list)
return res, nil
}

View File

@@ -0,0 +1,88 @@
// Package sys
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package sys
import (
"context"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/util/gconv"
"hotgo/api/backend/log"
"hotgo/internal/model/input/form"
"hotgo/internal/model/input/sysin"
"hotgo/internal/service"
)
// Log 日志
var Log = sLog{}
type sLog struct{}
// Clear 清空日志
func (c *sLog) Clear(ctx context.Context, req *log.ClearReq) (res *log.ClearRes, err error) {
err = gerror.New("考虑安全,请到数据库清空")
return
}
// Export 导出
func (c *sLog) Export(ctx context.Context, req *log.ExportReq) (res *log.ExportRes, err error) {
var in sysin.LogListInp
if err = gconv.Scan(req, &in); err != nil {
return nil, err
}
if err = service.SysLog().Export(ctx, in); err != nil {
return nil, err
}
return
}
// List 获取全局日志列表
func (c *sLog) List(ctx context.Context, req *log.ListReq) (*log.ListRes, error) {
var (
in sysin.LogListInp
res log.ListRes
)
if err := gconv.Scan(req, &in); err != nil {
return nil, err
}
list, totalCount, err := service.SysLog().List(ctx, in)
if err != nil {
return nil, err
}
res.List = list
res.PageCount = form.CalPageCount(totalCount, req.PerPage)
res.Page = req.Page
res.PerPage = req.PerPage
return &res, nil
}
// View 获取指定信息
func (c *sLog) View(ctx context.Context, req *log.ViewReq) (*log.ViewRes, error) {
var res log.ViewRes
data, err := service.SysLog().View(ctx, sysin.LogViewInp{Id: req.Id})
if err != nil {
return nil, err
}
res.LogViewModel = data
return &res, nil
}
// Delete 删除
func (c *sLog) Delete(ctx context.Context, req *log.DeleteReq) (res *log.DeleteRes, err error) {
var in sysin.LogDeleteInp
if err = gconv.Scan(req, &in); err != nil {
return nil, err
}
if err = service.SysLog().Delete(ctx, in); err != nil {
return nil, err
}
return res, nil
}

View File

@@ -0,0 +1,106 @@
// Package sys
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package sys
import (
"context"
"github.com/gogf/gf/v2/util/gconv"
"hotgo/api/backend/provinces"
"hotgo/internal/model/input/form"
"hotgo/internal/model/input/sysin"
"hotgo/internal/service"
)
var (
Provinces = cProvinces{}
)
type cProvinces struct{}
// Delete 删除
func (c *cProvinces) Delete(ctx context.Context, req *provinces.DeleteReq) (res *provinces.DeleteRes, err error) {
var in sysin.ProvincesDeleteInp
if err = gconv.Scan(req, &in); err != nil {
return nil, err
}
if err = service.SysProvinces().Delete(ctx, in); err != nil {
return nil, err
}
return res, nil
}
// Edit 更新
func (c *cProvinces) Edit(ctx context.Context, req *provinces.EditReq) (res *provinces.EditRes, err error) {
var in sysin.ProvincesEditInp
if err = gconv.Scan(req, &in); err != nil {
return nil, err
}
if err = service.SysProvinces().Edit(ctx, in); err != nil {
return nil, err
}
return res, nil
}
// MaxSort 最大排序
func (c *cProvinces) MaxSort(ctx context.Context, req *provinces.MaxSortReq) (*provinces.MaxSortRes, error) {
data, err := service.SysProvinces().MaxSort(ctx, sysin.ProvincesMaxSortInp{Id: req.Id})
if err != nil {
return nil, err
}
var res provinces.MaxSortRes
res.Sort = data.Sort
return &res, nil
}
// View 获取指定信息
func (c *cProvinces) View(ctx context.Context, req *provinces.ViewReq) (*provinces.ViewRes, error) {
data, err := service.SysProvinces().View(ctx, sysin.ProvincesViewInp{Id: req.Id})
if err != nil {
return nil, err
}
var res provinces.ViewRes
res.ProvincesViewModel = data
return &res, nil
}
// List 查看列表
func (c *cProvinces) List(ctx context.Context, req *provinces.ListReq) (*provinces.ListRes, error) {
var (
in sysin.ProvincesListInp
res provinces.ListRes
)
if err := gconv.Scan(req, &in); err != nil {
return nil, err
}
list, totalCount, err := service.SysProvinces().List(ctx, in)
if err != nil {
return nil, err
}
res.List = list
res.PageCount = form.CalPageCount(totalCount, req.PerPage)
res.Page = req.Page
res.PerPage = req.PerPage
return &res, nil
}
// Status 更新部门状态
func (c *cProvinces) Status(ctx context.Context, req *provinces.StatusReq) (res *provinces.StatusRes, err error) {
var in sysin.ProvincesStatusInp
if err = gconv.Scan(req, &in); err != nil {
return nil, err
}
if err = service.SysProvinces().Status(ctx, in); err != nil {
return nil, err
}
return res, nil
}

View File

@@ -0,0 +1,184 @@
// Package admin
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package admin
import (
"fmt"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gtime"
"github.com/gogf/gf/v2/util/gconv"
"github.com/shirou/gopsutil/cpu"
"github.com/shirou/gopsutil/disk"
"github.com/shirou/gopsutil/host"
"github.com/shirou/gopsutil/mem"
"github.com/shirou/gopsutil/process"
"hotgo/internal/consts"
"hotgo/internal/global"
"hotgo/internal/model"
"hotgo/internal/websocket"
"hotgo/utility/file"
"hotgo/utility/format"
"os"
"runtime"
"strconv"
"time"
)
var (
Monitor = cMonitor{}
)
type cMonitor struct{}
type MonitorHeadExtra struct {
Data interface{} `json:"data"`
Data1 string `json:"data1,omitempty"`
}
type MonitorHead struct {
Title string `json:"title"`
Data string `json:"data"`
BottomTitle string `json:"bottomTitle"`
TotalSum string `json:"totalSum"`
IconClass string `json:"iconClass"`
Extra MonitorHeadExtra `json:"extra"`
}
// RunInfo 运行信息
func (c *cMonitor) RunInfo(client *websocket.Client, req *websocket.WRequest) {
var (
data = g.Map{}
mHost, _ = host.Info()
pwd, _ = os.Getwd()
gm runtime.MemStats
)
runtime.ReadMemStats(&gm)
data = g.Map{
// 服务器信息
"hostname": mHost.Hostname,
"os": mHost.OS,
"arch": mHost.KernelArch,
"intranet_ip": global.MonitorData.IntranetIP,
"public_ip": global.MonitorData.PublicIP,
// GO运行信息
"goName": "Golang",
"version": runtime.Version(),
"startTime": global.MonitorData.STartTime,
"runTime": gtime.Now().Timestamp() - global.MonitorData.STartTime.Timestamp(),
"rootPath": runtime.GOROOT(),
"pwd": pwd,
"goroutine": runtime.NumGoroutine(),
"goMem": format.FileSize(int64(gm.Sys)),
"goSize": file.DirSize(pwd),
}
isDemo, _ := g.Cfg().Get(client.Context(), "hotgo.isDemo", false)
if isDemo.Bool() {
data["rootPath"] = consts.DemoTips
data["pwd"] = consts.DemoTips
data["intranet_ip"] = consts.DemoTips
data["public_ip"] = consts.DemoTips
}
websocket.SendSuccess(client, req.Event, data)
}
// Trends 实时数据
func (c *cMonitor) Trends(client *websocket.Client, req *websocket.WRequest) {
type NetC struct {
Time *gtime.Time `json:"time"`
BytesSent string `json:"bytesSent"` // number of bytes sent
BytesRecv string `json:"bytesRecv"` // number of bytes received
Down float64 `json:"down"`
UP float64 `json:"up"`
}
var (
mCpu, _ = cpu.Info()
mCpuUsed float64
mMem, _ = mem.VirtualMemory()
mMemUsed float64
mDisk, _ = disk.Usage("/")
mProcess, _ = process.Pids()
mLoadAvg *model.LoadAvgStats
data = g.Map{}
monitorHeads []MonitorHead
nets []NetC
)
// cpu使用率
cu, err := cpu.Percent(time.Second, false)
if err == nil {
mCpuUsed, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", cu[0]), 64)
}
// 内存使用率
mMemUsed, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", mMem.UsedPercent), 64)
// 负载
if len(global.MonitorData.LoadAvg) > 0 {
mLoadAvg = global.MonitorData.LoadAvg[len(global.MonitorData.LoadAvg)-1]
}
monitorHeads = append(monitorHeads, MonitorHead{
Title: "CPU",
Data: "使用率 " + format.Round2String(mCpuUsed) + "%",
BottomTitle: "CPU数量",
TotalSum: gconv.String(runtime.NumCPU()) + "核心",
IconClass: "HardwareChip",
Extra: MonitorHeadExtra{
Data: mCpu[0].VendorID,
Data1: mCpu[0].ModelName,
}},
MonitorHead{
Title: "内存",
Data: "使用率 " + format.Round2String(mMemUsed) + "%",
BottomTitle: "总内存",
TotalSum: format.FileSize(int64(mMem.Total)),
IconClass: "AppsSharp",
Extra: MonitorHeadExtra{
Data: format.FileSize(int64(mMem.Used)),
Data1: format.FileSize(int64(mMem.Total - mMem.Used)),
}},
MonitorHead{
Title: "磁盘",
Data: "已用 " + format.FileSize(int64(mDisk.Used)),
BottomTitle: "总容量",
TotalSum: format.FileSize(int64(mDisk.Total)),
IconClass: "PieChart",
Extra: MonitorHeadExtra{
Data: format.Round2String(mDisk.UsedPercent),
}},
MonitorHead{
Title: "负载",
Data: format.Round2String(mLoadAvg.Ratio) + "%",
BottomTitle: "总进程数",
TotalSum: gconv.String(len(mProcess)) + "个",
IconClass: "Analytics",
})
for _, v := range global.MonitorData.NetIO {
nets = append(nets, NetC{
Time: v.Time,
BytesSent: format.FileSize(int64(v.BytesSent)), // 转换为最大整数单位
BytesRecv: format.FileSize(int64(v.BytesRecv)),
Down: format.Round2Float64(v.Down / 1024), // 转换为kb
UP: format.Round2Float64(v.UP / 1024),
})
}
data = g.Map{
"head": monitorHeads,
"load": global.MonitorData.LoadAvg,
"net": nets,
}
websocket.SendSuccess(client, req.Event, data)
}

View File

@@ -0,0 +1,40 @@
// Package common
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package common
import (
"github.com/gogf/gf/v2/util/gconv"
"hotgo/internal/websocket"
)
var (
Site = cSite{}
)
type cSite struct{}
func (c *cSite) Join(client *websocket.Client, req *websocket.WRequest) {
name := gconv.String(req.Data["id"])
if !client.Tags.Contains(name) {
client.Tags.Append(name)
}
websocket.SendSuccess(client, req.Event, client.Tags.Slice())
}
func (c *cSite) Quit(client *websocket.Client, req *websocket.WRequest) {
name := gconv.String(req.Data["id"])
if client.Tags.Contains(name) {
client.Tags.RemoveValue(name)
}
websocket.SendSuccess(client, req.Event, client.Tags.Slice())
}
func (c *cSite) Ping(client *websocket.Client, req *websocket.WRequest) {
websocket.SendSuccess(client, req.Event)
}

View File

@@ -0,0 +1,28 @@
// Package websocket
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package websocket
import (
"context"
"hotgo/internal/model/input/websocketin"
"hotgo/internal/websocket"
)
// Send 通过http发送ws消息
var Send = send{}
type send struct{}
// ToTag 发送标签消息
func (c *send) ToTag(ctx context.Context, req *websocketin.SendToTagReq) (res *websocketin.SendToTagRes, err error) {
go websocket.SendToTag(req.Tag, &websocket.WResponse{
Event: req.Response.Event,
Data: req.Response,
})
return
}

View File

@@ -0,0 +1,199 @@
// Package crons
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package crons
import (
"context"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gcron"
"github.com/gogf/gf/v2/os/gctx"
"github.com/gogf/gf/v2/os/gtime"
"hotgo/internal/consts"
"hotgo/internal/dao"
"hotgo/internal/model/entity"
"strings"
"sync"
)
var (
// 添加新的任务时只需实现cronStrategy接口并加入到cronList即可
cronList = []cronStrategy{
Test, // 测试无参任务
Test2, // 测试有参任务
Monitor, // 监控
}
inst = new(tasks)
)
type cronStrategy interface {
GetName() string
Execute(ctx context.Context)
}
type tasks struct {
list []*TaskItem
sync.RWMutex
}
type TaskItem struct {
Pattern string // 表达式参考https://goframe.org/pages/viewpage.action?pageId=30736411
Name string // 唯一的任务名称
Params string // 函数参数,多个用,隔开
Fun gcron.JobFunc // 执行的函数接口
Policy int64 // 策略 1并行 2单例 3单次 4多次
Count int // 执行次数仅Policy=4时有效
}
func init() {
for _, cron := range cronList {
inst.Add(&TaskItem{
Name: cron.GetName(),
Fun: cron.Execute,
})
}
}
func StopALL() {
for _, v := range gcron.Entries() {
gcron.Remove(v.Name)
}
}
// StartALL 启动任务
func StartALL(sysCron []*entity.SysCron) error {
var (
err error
ct = gctx.New()
)
if len(sysCron) == 0 {
g.Log().Info(ct, "没有可用的定时任务")
return nil
}
for _, cron := range sysCron {
f := inst.Get(cron.Name)
if f == nil {
return gerror.Newf("该任务没有加入任务列表:%v", cron.Name)
}
// 没有则添加
if gcron.Search(cron.Name) == nil {
var (
t *gcron.Entry
ctx = context.WithValue(gctx.New(), consts.CronArgsKey, strings.Split(cron.Params, consts.CronSplitStr))
)
switch cron.Policy {
case consts.CronPolicySame:
t, err = gcron.Add(ctx, cron.Pattern, f.Fun, cron.Name)
case consts.CronPolicySingle:
t, err = gcron.AddSingleton(ctx, cron.Pattern, f.Fun, cron.Name)
case consts.CronPolicyOnce:
t, err = gcron.AddOnce(ctx, cron.Pattern, f.Fun, cron.Name)
case consts.CronPolicyTimes:
if f.Count <= 0 {
f.Count = 1
}
t, err = gcron.AddTimes(ctx, cron.Pattern, int(cron.Count), f.Fun, cron.Name)
default:
return gerror.Newf("使用无效的策略, cron.Policy=%v", cron.Policy)
}
if err != nil {
return err
}
if t == nil {
return gerror.New("启动任务失败")
}
}
gcron.Start(cron.Name)
// 执行完毕,单次和多次执行的任务更新状态
if cron.Policy == consts.CronPolicyOnce || cron.Policy == consts.CronPolicyTimes {
_, err = dao.SysCron.Ctx(ct).Where("id", cron.Id).
Data(g.Map{"status": consts.StatusDisable, "updated_at": gtime.Now()}).
Update()
if err != nil {
err = gerror.Wrap(err, consts.ErrorORM)
return err
}
}
}
g.Log().Info(ct, "定时任务启动完毕...")
return nil
}
// Stop 停止单个任务
func Stop(sysCron *entity.SysCron) error {
return nil
}
// Once 立即执行一次某个任务
func Once(sysCron *entity.SysCron) error {
return nil
}
// Delete 删除任务
func Delete(sysCron *entity.SysCron) error {
// ...
return Stop(sysCron)
}
// Start 启动单个任务
func Start(sysCron *entity.SysCron) error {
return nil
}
// Add 添加任务
func (t *tasks) Add(task *TaskItem) *tasks {
if task.Name == "" || task.Fun == nil {
return t
}
t.Lock()
defer t.Unlock()
t.list = append(t.list, task)
return t
}
// Get 找到任务
func (t *tasks) Get(name string) *TaskItem {
if len(t.list) == 0 {
return nil
}
for _, item := range t.list {
if item.Name == name {
return item
}
}
return nil
}
// Del 删除任务
func (t *tasks) Del(name string) (newList []*TaskItem) {
if len(t.list) == 0 {
return nil
}
t.Lock()
defer t.Unlock()
for _, item := range t.list {
if item.Name == name {
continue
}
newList = append(newList, item)
}
return newList
}

View File

@@ -0,0 +1,75 @@
// Package crons
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package crons
import (
"context"
"github.com/gogf/gf/v2/os/gtime"
"github.com/shirou/gopsutil/load"
"github.com/shirou/gopsutil/net"
"hotgo/internal/global"
"hotgo/internal/model"
"hotgo/utility/format"
"runtime"
"sync"
)
// Monitor 监控
var Monitor = &cMonitor{name: "monitor"}
type cMonitor struct {
name string
sync.RWMutex
}
func (c *cMonitor) GetName() string {
return c.name
}
// Execute 执行任务
func (c *cMonitor) Execute(ctx context.Context) {
c.Lock()
defer c.Unlock()
c.NetIO()
c.loadAvg()
}
func (c *cMonitor) loadAvg() {
pl, _ := load.Avg()
counter := model.LoadAvgStats{
Time: gtime.Now(),
Avg: pl.Load1,
Ratio: pl.Load1 / (float64(runtime.NumCPU()) * 2) * 100,
}
global.MonitorData.LoadAvg = append(global.MonitorData.LoadAvg, &counter)
if len(global.MonitorData.LoadAvg) > 10 {
global.MonitorData.LoadAvg = append(global.MonitorData.LoadAvg[:0], global.MonitorData.LoadAvg[(1):]...)
}
}
func (c *cMonitor) NetIO() {
var counter model.NetIOCounters
ni, _ := net.IOCounters(true)
counter.Time = gtime.Now()
for _, v := range ni {
counter.BytesSent += v.BytesSent
counter.BytesRecv += v.BytesRecv
}
if len(global.MonitorData.NetIO) > 0 {
lastNetIO := global.MonitorData.NetIO[len(global.MonitorData.NetIO)-1]
sub := counter.Time.Sub(lastNetIO.Time).Seconds()
counter.Down = format.Round2Float64((float64(counter.BytesRecv - lastNetIO.BytesRecv)) / sub)
counter.UP = format.Round2Float64((float64(counter.BytesSent - lastNetIO.BytesSent)) / sub)
}
global.MonitorData.NetIO = append(global.MonitorData.NetIO, &counter)
if len(global.MonitorData.NetIO) > 10 {
global.MonitorData.NetIO = append(global.MonitorData.NetIO[:0], global.MonitorData.NetIO[(1):]...)
}
}

View File

@@ -0,0 +1,29 @@
// Package crons
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package crons
import (
"context"
"github.com/gogf/gf/v2/frame/g"
"time"
)
// Test 测试任务
var Test = &cTest{name: "test"}
type cTest struct {
name string
}
func (c *cTest) GetName() string {
return c.name
}
// Execute 执行任务
func (c *cTest) Execute(ctx context.Context) {
g.Log().Infof(ctx, "cron test Execute:%v", time.Now())
}

View File

@@ -0,0 +1,46 @@
// Package crons
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package crons
import (
"context"
"github.com/gogf/gf/v2/frame/g"
"hotgo/internal/consts"
"time"
)
// Test2 测试2任务
var Test2 = &cTest2{name: "test2"}
type cTest2 struct {
name string
}
func (c *cTest2) GetName() string {
return c.name
}
// Execute 执行任务
func (c *cTest2) Execute(ctx context.Context) {
args, ok := ctx.Value(consts.CronArgsKey).([]string)
if !ok {
g.Log().Warning(ctx, "参数解析失败!")
return
}
if len(args) != 3 {
g.Log().Warning(ctx, "test2 传入参数不正确!")
return
}
var (
name = args[0]
age = args[1]
msg = args[2]
)
g.Log().Infof(ctx, "cron test2 Execute:%v, name:%v, age:%v, msg:%v", time.Now(), name, age, msg)
}

View File

View File

@@ -0,0 +1,65 @@
// =================================================================================
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
// =================================================================================
package dao
import (
"context"
"github.com/gogf/gf/v2/errors/gerror"
"hotgo/internal/consts"
"hotgo/internal/dao/internal"
"hotgo/internal/model/entity"
)
// internalAdminDeptDao is internal type for wrapping internal DAO implements.
type internalAdminDeptDao = *internal.AdminDeptDao
// adminDeptDao is the data access object for table hg_admin_dept.
// You can define custom methods on it to extend its functionality as you wish.
type adminDeptDao struct {
internalAdminDeptDao
}
var (
// AdminDept is globally common accessible object for table hg_admin_dept operations.
AdminDept = adminDeptDao{
internal.NewAdminDeptDao(),
}
)
// IsUniqueName 判断名称是否唯一
func (dao *adminDeptDao) IsUniqueName(ctx context.Context, id int64, name string) (bool, error) {
var data *entity.AdminDept
m := dao.Ctx(ctx).Where("name", name)
if id > 0 {
m = m.WhereNot("id", id)
}
if err := m.Scan(&data); err != nil {
err = gerror.Wrap(err, consts.ErrorORM)
return false, err
}
if data == nil {
return true, nil
}
return false, nil
}
// TopPid 获取最上级pid
func (dao *adminDeptDao) TopPid(ctx context.Context, data *entity.AdminDept) (int64, error) {
var pidData *entity.AdminDept
if data.Pid == 0 {
return data.Id, nil
}
err := dao.Ctx(ctx).Where("id", data.Pid).Scan(&pidData)
if err != nil {
err = gerror.Wrap(err, consts.ErrorORM)
return 0, err
}
return dao.TopPid(ctx, pidData)
}

View File

@@ -0,0 +1,119 @@
// =================================================================================
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
// =================================================================================
package dao
import (
"context"
"github.com/gogf/gf/v2/errors/gerror"
"hotgo/internal/consts"
"hotgo/internal/dao/internal"
"hotgo/internal/model/entity"
)
// internalAdminMemberDao is internal type for wrapping internal DAO implements.
type internalAdminMemberDao = *internal.AdminMemberDao
// adminMemberDao is the data access object for table hg_admin_member.
// You can define custom methods on it to extend its functionality as you wish.
type adminMemberDao struct {
internalAdminMemberDao
}
var (
// AdminMember is globally common accessible object for table hg_admin_member operations.
AdminMember = adminMemberDao{
internal.NewAdminMemberDao(),
}
)
// Fill with you ideas below.
// IsUniqueName 判断用户名是否唯一
// @Description:
// @receiver dao
// @param ctx
// @param id
// @param name
// @return bool
// @return error
//
func (dao *adminMemberDao) IsUniqueName(ctx context.Context, id int64, name string) (bool, error) {
var data *entity.AdminDept
m := dao.Ctx(ctx).Where("username", name)
if id > 0 {
m = m.WhereNot("id", id)
}
if err := m.Scan(&data); err != nil {
err = gerror.Wrap(err, consts.ErrorORM)
return false, err
}
if data == nil {
return true, nil
}
return false, nil
}
// IsUniqueEmail 判断邮箱是否唯一
// @Description:
// @receiver dao
// @param ctx
// @param id
// @param email
// @return bool
// @return error
//
func (dao *adminMemberDao) IsUniqueEmail(ctx context.Context, id int64, email string) (bool, error) {
var data *entity.AdminMember
m := dao.Ctx(ctx).Where("email", email)
if id > 0 {
m = m.WhereNot("id", id)
}
if err := m.Scan(&data); err != nil {
err = gerror.Wrap(err, consts.ErrorORM)
return false, err
}
if data == nil {
return true, nil
}
return false, nil
}
// IsUniqueMobile 判断手机号是否唯一
// @Description:
// @receiver dao
// @param ctx
// @param id
// @param mobile
// @return bool
// @return error
//
func (dao *adminMemberDao) IsUniqueMobile(ctx context.Context, id int64, mobile string) (bool, error) {
var data *entity.AdminMember
m := dao.Ctx(ctx).Where("mobile", mobile)
if id > 0 {
m = m.WhereNot("id", id)
}
if err := m.Scan(&data); err != nil {
err = gerror.Wrap(err, consts.ErrorORM)
return false, err
}
if data == nil {
return true, nil
}
return false, nil
}

View File

@@ -0,0 +1,90 @@
// =================================================================================
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
// =================================================================================
package dao
import (
"context"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g"
"hotgo/internal/consts"
"hotgo/internal/dao/internal"
"hotgo/internal/model/entity"
)
// internalAdminMemberPostDao is internal type for wrapping internal DAO implements.
type internalAdminMemberPostDao = *internal.AdminMemberPostDao
// adminMemberPostDao is the data access object for table hg_admin_member_post.
// You can define custom methods on it to extend its functionality as you wish.
type adminMemberPostDao struct {
internalAdminMemberPostDao
}
var (
// AdminMemberPost is globally common accessible object for table hg_admin_member_post operations.
AdminMemberPost = adminMemberPostDao{
internal.NewAdminMemberPostDao(),
}
)
// UpdatePostIds
// @Description:
// @receiver dao
// @param ctx
// @param memberId
// @param postIds
// @return err
//
func (dao *adminMemberPostDao) UpdatePostIds(ctx context.Context, memberId int64, postIds []int64) (err error) {
_, err = dao.Ctx(ctx).
Where("member_id", memberId).
Delete()
if err != nil {
err = gerror.Wrap(err, "删除失败")
return err
}
for i := 0; i < len(postIds); i++ {
_, err = dao.Ctx(ctx).
Insert(entity.AdminMemberPost{
MemberId: memberId,
PostId: postIds[i],
})
if err != nil {
err = gerror.Wrap(err, "插入会员岗位失败")
return err
}
}
return nil
}
// GetMemberByIds 获取指定会员的岗位ids
// @Description:
// @receiver dao
// @param ctx
// @param memberId
// @return postIds
// @return err
//
func (dao *adminMemberPostDao) GetMemberByIds(ctx context.Context, memberId int64) (postIds []int64, err error) {
var list []*entity.AdminMemberPost
err = dao.Ctx(ctx).
Fields("post_id").
Where("member_id", memberId).
Scan(&list)
if err != nil {
err = gerror.Wrap(err, consts.ErrorORM)
return postIds, err
}
for i := 0; i < len(list); i++ {
postIds = append(postIds, list[i].PostId)
}
g.Log().Print(ctx, "post_ids:", postIds)
return postIds, nil
}

View File

@@ -0,0 +1,27 @@
// =================================================================================
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
// =================================================================================
package dao
import (
"hotgo/internal/dao/internal"
)
// internalAdminMemberRoleDao is internal type for wrapping internal DAO implements.
type internalAdminMemberRoleDao = *internal.AdminMemberRoleDao
// adminMemberRoleDao is the data access object for table hg_admin_member_role.
// You can define custom methods on it to extend its functionality as you wish.
type adminMemberRoleDao struct {
internalAdminMemberRoleDao
}
var (
// AdminMemberRole is globally common accessible object for table hg_admin_member_role operations.
AdminMemberRole = adminMemberRoleDao{
internal.NewAdminMemberRoleDao(),
}
)
// Fill with you ideas below.

View File

@@ -0,0 +1,165 @@
// =================================================================================
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
// =================================================================================
package dao
import (
"context"
"github.com/gogf/gf/v2/errors/gerror"
"hotgo/internal/consts"
"hotgo/internal/dao/internal"
"hotgo/internal/model"
"hotgo/internal/model/entity"
)
// internalAdminMenuDao is internal type for wrapping internal DAO implements.
type internalAdminMenuDao = *internal.AdminMenuDao
// adminMenuDao is the data access object for table hg_admin_menu.
// You can define custom methods on it to extend its functionality as you wish.
type adminMenuDao struct {
internalAdminMenuDao
}
var (
// AdminMenu is globally common accessible object for table hg_admin_menu operations.
AdminMenu = adminMenuDao{
internal.NewAdminMenuDao(),
}
)
// IsUniqueTitle 判断标题是否唯一
func (dao *adminMenuDao) IsUniqueTitle(ctx context.Context, id int64, title string) (bool, error) {
var data *entity.AdminMenu
m := dao.Ctx(ctx).Where("title", title)
if id > 0 {
m = m.WhereNot("id", id)
}
if err := m.Scan(&data); err != nil {
err = gerror.Wrap(err, consts.ErrorORM)
return false, err
}
if data == nil {
return true, nil
}
return false, nil
}
// IsUniqueName 判断编码是否唯一
func (dao *adminMenuDao) IsUniqueName(ctx context.Context, id int64, name string) (bool, error) {
var data *entity.AdminMenu
m := dao.Ctx(ctx).Where("name", name)
if id > 0 {
m = m.WhereNot("id", id)
}
if err := m.Scan(&data); err != nil {
err = gerror.Wrap(err, consts.ErrorORM)
return false, err
}
if data == nil {
return true, nil
}
return false, nil
}
// GenLabelTreeList
func (dao *adminMenuDao) GenLabelTreeList(ctx context.Context, pid int64) ([]*model.LabelTreeMenu, error) {
var (
newLst []*model.LabelTreeMenu
)
if err := dao.Ctx(ctx).Where("pid", pid).Order("sort asc,id desc").Scan(&newLst); err != nil {
err = gerror.Wrap(err, consts.ErrorORM)
return nil, err
}
for i := 0; i < len(newLst); i++ {
newLst[i].Key = newLst[i].Id
newLst[i].Label = newLst[i].Name
err := dao.Ctx(ctx).Where("pid", newLst[i].Id).Order("sort asc,id desc").Scan(&newLst[i].Children)
if err != nil {
err = gerror.Wrap(err, consts.ErrorORM)
return nil, err
}
for i2 := 0; i2 < len(newLst[i].Children); i2++ {
newLst[i].Children[i2].Key = newLst[i].Children[i2].Id
newLst[i].Children[i2].Label = newLst[i].Children[i2].Name
}
}
return newLst, nil
}
//
//  @Title  生成树列表
//  @Description
//  @Author  Ms <133814250@qq.com>
//  @Param   ctx
//  @Param   pid
//  @Param   lists
//  @Return  []*model.TreeMenu
//  @Return  error
//
func (dao *adminMenuDao) GenTreeList(ctx context.Context, pid int64, ids []int64) ([]*model.TreeMenu, error) {
var (
newLst []*model.TreeMenu
)
if err := dao.Ctx(ctx).Where("id", ids).Where("pid", pid).Order("sort asc,id desc").Scan(&newLst); err != nil {
err = gerror.Wrap(err, consts.ErrorORM)
return nil, err
}
for i := 0; i < len(newLst); i++ {
err := dao.Ctx(ctx).Where("pid", newLst[i].Id).Order("sort asc,id desc").Scan(&newLst[i].Children)
if err != nil {
err = gerror.Wrap(err, consts.ErrorORM)
return nil, err
}
}
return newLst, nil
}
//
//  @Title  获取最上级pid
//  @Description
//  @Author  Ms <133814250@qq.com>
//  @Param   ctx
//  @Param   data
//  @Return  int64
//  @Return  error
//
//
// TopPid
// @Description:
// @receiver dao
// @param ctx
// @param data
// @return int64
// @return error
//
func (dao *adminMenuDao) TopPid(ctx context.Context, data *entity.AdminMenu) (int64, error) {
var pidData *entity.AdminMenu
if data.Pid == 0 {
return data.Id, nil
}
err := dao.Ctx(ctx).Where("id", data.Pid).Scan(&pidData)
if err != nil {
err = gerror.Wrap(err, consts.ErrorORM)
return 0, err
}
return dao.TopPid(ctx, pidData)
}

View File

@@ -0,0 +1,27 @@
// =================================================================================
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
// =================================================================================
package dao
import (
"hotgo/internal/dao/internal"
)
// internalAdminNoticeDao is internal type for wrapping internal DAO implements.
type internalAdminNoticeDao = *internal.AdminNoticeDao
// adminNoticeDao is the data access object for table hg_admin_notice.
// You can define custom methods on it to extend its functionality as you wish.
type adminNoticeDao struct {
internalAdminNoticeDao
}
var (
// AdminNotice is globally common accessible object for table hg_admin_notice operations.
AdminNotice = adminNoticeDao{
internal.NewAdminNoticeDao(),
}
)
// Fill with you ideas below.

View File

@@ -0,0 +1,71 @@
// =================================================================================
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
// =================================================================================
package dao
import (
"context"
"github.com/gogf/gf/v2/errors/gerror"
"hotgo/internal/consts"
"hotgo/internal/dao/internal"
"hotgo/internal/model/entity"
)
// internalAdminPostDao is internal type for wrapping internal DAO implements.
type internalAdminPostDao = *internal.AdminPostDao
// adminPostDao is the data access object for table hg_admin_post.
// You can define custom methods on it to extend its functionality as you wish.
type adminPostDao struct {
internalAdminPostDao
}
var (
// AdminPost is globally common accessible object for table hg_admin_post operations.
AdminPost = adminPostDao{
internal.NewAdminPostDao(),
}
)
// IsUniqueName 判断名称是否唯一
func (dao *adminPostDao) IsUniqueName(ctx context.Context, id int64, name string) (bool, error) {
var data *entity.AdminPost
m := dao.Ctx(ctx).Where("name", name)
if id > 0 {
m = m.WhereNot("id", id)
}
if err := m.Scan(&data); err != nil {
err = gerror.Wrap(err, consts.ErrorORM)
return false, err
}
if data == nil {
return true, nil
}
return false, nil
}
// IsUniqueCode 判断编码是否唯一
func (dao *adminPostDao) IsUniqueCode(ctx context.Context, id int64, code string) (bool, error) {
var data *entity.AdminPost
m := dao.Ctx(ctx).Where("code", code)
if id > 0 {
m = m.WhereNot("id", id)
}
if err := m.Scan(&data); err != nil {
err = gerror.Wrap(err, consts.ErrorORM)
return false, err
}
if data == nil {
return true, nil
}
return false, nil
}

View File

@@ -0,0 +1,71 @@
// =================================================================================
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
// =================================================================================
package dao
import (
"context"
"github.com/gogf/gf/v2/errors/gerror"
"hotgo/internal/consts"
"hotgo/internal/dao/internal"
"hotgo/internal/model/entity"
)
// internalAdminRoleDao is internal type for wrapping internal DAO implements.
type internalAdminRoleDao = *internal.AdminRoleDao
// adminRoleDao is the data access object for table hg_admin_role.
// You can define custom methods on it to extend its functionality as you wish.
type adminRoleDao struct {
internalAdminRoleDao
}
var (
// AdminRole is globally common accessible object for table hg_admin_role operations.
AdminRole = adminRoleDao{
internal.NewAdminRoleDao(),
}
)
// IsUniqueName 判断名称是否唯一
func (dao *adminRoleDao) IsUniqueName(ctx context.Context, id int64, name string) (bool, error) {
var data *entity.AdminRole
m := dao.Ctx(ctx).Where("name", name)
if id > 0 {
m = m.WhereNot("id", id)
}
if err := m.Scan(&data); err != nil {
err = gerror.Wrap(err, consts.ErrorORM)
return false, err
}
if data == nil {
return true, nil
}
return false, nil
}
// IsUniqueCode 判断编码是否唯一
func (dao *adminRoleDao) IsUniqueCode(ctx context.Context, id int64, code string) (bool, error) {
var data *entity.AdminRole
m := dao.Ctx(ctx).Where("key", code)
if id > 0 {
m = m.WhereNot("id", id)
}
if err := m.Scan(&data); err != nil {
err = gerror.Wrap(err, consts.ErrorORM)
return false, err
}
if data == nil {
return true, nil
}
return false, nil
}

View File

@@ -0,0 +1,27 @@
// =================================================================================
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
// =================================================================================
package dao
import (
"hotgo/internal/dao/internal"
)
// internalAdminRoleCasbinDao is internal type for wrapping internal DAO implements.
type internalAdminRoleCasbinDao = *internal.AdminRoleCasbinDao
// adminRoleCasbinDao is the data access object for table hg_admin_role_casbin.
// You can define custom methods on it to extend its functionality as you wish.
type adminRoleCasbinDao struct {
internalAdminRoleCasbinDao
}
var (
// AdminRoleCasbin is globally public accessible object for table hg_admin_role_casbin operations.
AdminRoleCasbin = adminRoleCasbinDao{
internal.NewAdminRoleCasbinDao(),
}
)
// Fill with you ideas below.

View File

@@ -0,0 +1,27 @@
// =================================================================================
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
// =================================================================================
package dao
import (
"hotgo/internal/dao/internal"
)
// internalAdminRoleDeptDao is internal type for wrapping internal DAO implements.
type internalAdminRoleDeptDao = *internal.AdminRoleDeptDao
// adminRoleDeptDao is the data access object for table hg_admin_role_dept.
// You can define custom methods on it to extend its functionality as you wish.
type adminRoleDeptDao struct {
internalAdminRoleDeptDao
}
var (
// AdminRoleDept is globally common accessible object for table hg_admin_role_dept operations.
AdminRoleDept = adminRoleDeptDao{
internal.NewAdminRoleDeptDao(),
}
)
// Fill with you ideas below.

View File

@@ -0,0 +1,27 @@
// =================================================================================
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
// =================================================================================
package dao
import (
"hotgo/internal/dao/internal"
)
// internalAdminRoleMenuDao is internal type for wrapping internal DAO implements.
type internalAdminRoleMenuDao = *internal.AdminRoleMenuDao
// adminRoleMenuDao is the data access object for table hg_admin_role_menu.
// You can define custom methods on it to extend its functionality as you wish.
type adminRoleMenuDao struct {
internalAdminRoleMenuDao
}
var (
// AdminRoleMenu is globally common accessible object for table hg_admin_role_menu operations.
AdminRoleMenu = adminRoleMenuDao{
internal.NewAdminRoleMenuDao(),
}
)
// Fill with you ideas below.

View File

@@ -0,0 +1,95 @@
// ==========================================================================
// Code generated by GoFrame CLI tool. DO NOT EDIT.
// ==========================================================================
package internal
import (
"context"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
)
// AdminDeptDao is the data access object for table hg_admin_dept.
type AdminDeptDao struct {
table string // table is the underlying table name of the DAO.
group string // group is the database configuration group name of current DAO.
columns AdminDeptColumns // columns contains all the column names of Table for convenient usage.
}
// AdminDeptColumns defines and stores column names for table hg_admin_dept.
type AdminDeptColumns struct {
Id string // 部门id
Pid string // 父部门id
Name string // 部门名称
Code string // 部门编码
Type string // 部门类型
Leader string // 负责人
Phone string // 联系电话
Email string // 邮箱
Sort string // 排序
Status string // 部门状态
CreatedAt string // 创建时间
UpdatedAt string // 更新时间
}
// adminDeptColumns holds the columns for table hg_admin_dept.
var adminDeptColumns = AdminDeptColumns{
Id: "id",
Pid: "pid",
Name: "name",
Code: "code",
Type: "type",
Leader: "leader",
Phone: "phone",
Email: "email",
Sort: "sort",
Status: "status",
CreatedAt: "created_at",
UpdatedAt: "updated_at",
}
// NewAdminDeptDao creates and returns a new DAO object for table data access.
func NewAdminDeptDao() *AdminDeptDao {
return &AdminDeptDao{
group: "default",
table: "hg_admin_dept",
columns: adminDeptColumns,
}
}
// DB retrieves and returns the underlying raw database management object of current DAO.
func (dao *AdminDeptDao) DB() gdb.DB {
return g.DB(dao.group)
}
// Table returns the table name of current dao.
func (dao *AdminDeptDao) Table() string {
return dao.table
}
// Columns returns all column names of current dao.
func (dao *AdminDeptDao) Columns() AdminDeptColumns {
return dao.columns
}
// Group returns the configuration group name of database of current dao.
func (dao *AdminDeptDao) Group() string {
return dao.group
}
// Ctx creates and returns the Model for current DAO, It automatically sets the context for current operation.
func (dao *AdminDeptDao) Ctx(ctx context.Context) *gdb.Model {
return dao.DB().Model(dao.table).Safe().Ctx(ctx)
}
// Transaction wraps the transaction logic using function f.
// It rollbacks the transaction and returns the error from function f if it returns non-nil error.
// It commits the transaction and returns nil if function f returns nil.
//
// Note that, you should not Commit or Rollback the transaction in function f
// as it is automatically handled by this function.
func (dao *AdminDeptDao) Transaction(ctx context.Context, f func(ctx context.Context, tx *gdb.TX) error) (err error) {
return dao.Ctx(ctx).Transaction(ctx, f)
}

View File

@@ -0,0 +1,129 @@
// ==========================================================================
// Code generated by GoFrame CLI tool. DO NOT EDIT.
// ==========================================================================
package internal
import (
"context"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
)
// AdminMemberDao is the data access object for table hg_admin_member.
type AdminMemberDao struct {
table string // table is the underlying table name of the DAO.
group string // group is the database configuration group name of current DAO.
columns AdminMemberColumns // columns contains all the column names of Table for convenient usage.
}
// AdminMemberColumns defines and stores column names for table hg_admin_member.
type AdminMemberColumns struct {
Id string //
DeptId string // 部门ID
Username string // 帐号
PasswordHash string // 密码
Salt string // 密码盐
AuthKey string // 授权令牌
PasswordResetToken string // 密码重置令牌
Type string // 1:普通管理员;10超级管理员
Realname string // 真实姓名
Avatar string // 头像
Sex string // 性别[1:男;2:女;3:未知]
Qq string // qq
Email string // 邮箱
Birthday string // 生日
ProvinceId string // 省
CityId string // 城市
AreaId string // 地区
Address string // 默认地址
Mobile string // 手机号码
HomePhone string // 家庭号码
DingtalkRobotToken string // 钉钉机器人token
VisitCount string // 访问次数
LastTime string // 最后一次登录时间
LastIp string // 最后一次登录ip
Role string // 权限
Remark string // 备注
Status string // 状态
CreatedAt string // 创建时间
UpdatedAt string // 修改时间
}
// adminMemberColumns holds the columns for table hg_admin_member.
var adminMemberColumns = AdminMemberColumns{
Id: "id",
DeptId: "dept_id",
Username: "username",
PasswordHash: "password_hash",
Salt: "salt",
AuthKey: "auth_key",
PasswordResetToken: "password_reset_token",
Type: "type",
Realname: "realname",
Avatar: "avatar",
Sex: "sex",
Qq: "qq",
Email: "email",
Birthday: "birthday",
ProvinceId: "province_id",
CityId: "city_id",
AreaId: "area_id",
Address: "address",
Mobile: "mobile",
HomePhone: "home_phone",
DingtalkRobotToken: "dingtalk_robot_token",
VisitCount: "visit_count",
LastTime: "last_time",
LastIp: "last_ip",
Role: "role",
Remark: "remark",
Status: "status",
CreatedAt: "created_at",
UpdatedAt: "updated_at",
}
// NewAdminMemberDao creates and returns a new DAO object for table data access.
func NewAdminMemberDao() *AdminMemberDao {
return &AdminMemberDao{
group: "default",
table: "hg_admin_member",
columns: adminMemberColumns,
}
}
// DB retrieves and returns the underlying raw database management object of current DAO.
func (dao *AdminMemberDao) DB() gdb.DB {
return g.DB(dao.group)
}
// Table returns the table name of current dao.
func (dao *AdminMemberDao) Table() string {
return dao.table
}
// Columns returns all column names of current dao.
func (dao *AdminMemberDao) Columns() AdminMemberColumns {
return dao.columns
}
// Group returns the configuration group name of database of current dao.
func (dao *AdminMemberDao) Group() string {
return dao.group
}
// Ctx creates and returns the Model for current DAO, It automatically sets the context for current operation.
func (dao *AdminMemberDao) Ctx(ctx context.Context) *gdb.Model {
return dao.DB().Model(dao.table).Safe().Ctx(ctx)
}
// Transaction wraps the transaction logic using function f.
// It rollbacks the transaction and returns the error from function f if it returns non-nil error.
// It commits the transaction and returns nil if function f returns nil.
//
// Note that, you should not Commit or Rollback the transaction in function f
// as it is automatically handled by this function.
func (dao *AdminMemberDao) Transaction(ctx context.Context, f func(ctx context.Context, tx *gdb.TX) error) (err error) {
return dao.Ctx(ctx).Transaction(ctx, f)
}

View File

@@ -0,0 +1,75 @@
// ==========================================================================
// Code generated by GoFrame CLI tool. DO NOT EDIT.
// ==========================================================================
package internal
import (
"context"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
)
// AdminMemberPostDao is the data access object for table hg_admin_member_post.
type AdminMemberPostDao struct {
table string // table is the underlying table name of the DAO.
group string // group is the database configuration group name of current DAO.
columns AdminMemberPostColumns // columns contains all the column names of Table for convenient usage.
}
// AdminMemberPostColumns defines and stores column names for table hg_admin_member_post.
type AdminMemberPostColumns struct {
MemberId string // 用户ID
PostId string // 岗位ID
}
// adminMemberPostColumns holds the columns for table hg_admin_member_post.
var adminMemberPostColumns = AdminMemberPostColumns{
MemberId: "member_id",
PostId: "post_id",
}
// NewAdminMemberPostDao creates and returns a new DAO object for table data access.
func NewAdminMemberPostDao() *AdminMemberPostDao {
return &AdminMemberPostDao{
group: "default",
table: "hg_admin_member_post",
columns: adminMemberPostColumns,
}
}
// DB retrieves and returns the underlying raw database management object of current DAO.
func (dao *AdminMemberPostDao) DB() gdb.DB {
return g.DB(dao.group)
}
// Table returns the table name of current dao.
func (dao *AdminMemberPostDao) Table() string {
return dao.table
}
// Columns returns all column names of current dao.
func (dao *AdminMemberPostDao) Columns() AdminMemberPostColumns {
return dao.columns
}
// Group returns the configuration group name of database of current dao.
func (dao *AdminMemberPostDao) Group() string {
return dao.group
}
// Ctx creates and returns the Model for current DAO, It automatically sets the context for current operation.
func (dao *AdminMemberPostDao) Ctx(ctx context.Context) *gdb.Model {
return dao.DB().Model(dao.table).Safe().Ctx(ctx)
}
// Transaction wraps the transaction logic using function f.
// It rollbacks the transaction and returns the error from function f if it returns non-nil error.
// It commits the transaction and returns nil if function f returns nil.
//
// Note that, you should not Commit or Rollback the transaction in function f
// as it is automatically handled by this function.
func (dao *AdminMemberPostDao) Transaction(ctx context.Context, f func(ctx context.Context, tx *gdb.TX) error) (err error) {
return dao.Ctx(ctx).Transaction(ctx, f)
}

View File

@@ -0,0 +1,75 @@
// ==========================================================================
// Code generated by GoFrame CLI tool. DO NOT EDIT.
// ==========================================================================
package internal
import (
"context"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
)
// AdminMemberRoleDao is the data access object for table hg_admin_member_role.
type AdminMemberRoleDao struct {
table string // table is the underlying table name of the DAO.
group string // group is the database configuration group name of current DAO.
columns AdminMemberRoleColumns // columns contains all the column names of Table for convenient usage.
}
// AdminMemberRoleColumns defines and stores column names for table hg_admin_member_role.
type AdminMemberRoleColumns struct {
MemberId string // 用户ID
RoleId string // 角色ID
}
// adminMemberRoleColumns holds the columns for table hg_admin_member_role.
var adminMemberRoleColumns = AdminMemberRoleColumns{
MemberId: "member_id",
RoleId: "role_id",
}
// NewAdminMemberRoleDao creates and returns a new DAO object for table data access.
func NewAdminMemberRoleDao() *AdminMemberRoleDao {
return &AdminMemberRoleDao{
group: "default",
table: "hg_admin_member_role",
columns: adminMemberRoleColumns,
}
}
// DB retrieves and returns the underlying raw database management object of current DAO.
func (dao *AdminMemberRoleDao) DB() gdb.DB {
return g.DB(dao.group)
}
// Table returns the table name of current dao.
func (dao *AdminMemberRoleDao) Table() string {
return dao.table
}
// Columns returns all column names of current dao.
func (dao *AdminMemberRoleDao) Columns() AdminMemberRoleColumns {
return dao.columns
}
// Group returns the configuration group name of database of current dao.
func (dao *AdminMemberRoleDao) Group() string {
return dao.group
}
// Ctx creates and returns the Model for current DAO, It automatically sets the context for current operation.
func (dao *AdminMemberRoleDao) Ctx(ctx context.Context) *gdb.Model {
return dao.DB().Model(dao.table).Safe().Ctx(ctx)
}
// Transaction wraps the transaction logic using function f.
// It rollbacks the transaction and returns the error from function f if it returns non-nil error.
// It commits the transaction and returns nil if function f returns nil.
//
// Note that, you should not Commit or Rollback the transaction in function f
// as it is automatically handled by this function.
func (dao *AdminMemberRoleDao) Transaction(ctx context.Context, f func(ctx context.Context, tx *gdb.TX) error) (err error) {
return dao.Ctx(ctx).Transaction(ctx, f)
}

View File

@@ -0,0 +1,123 @@
// ==========================================================================
// Code generated by GoFrame CLI tool. DO NOT EDIT.
// ==========================================================================
package internal
import (
"context"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
)
// AdminMenuDao is the data access object for table hg_admin_menu.
type AdminMenuDao struct {
table string // table is the underlying table name of the DAO.
group string // group is the database configuration group name of current DAO.
columns AdminMenuColumns // columns contains all the column names of Table for convenient usage.
}
// AdminMenuColumns defines and stores column names for table hg_admin_menu.
type AdminMenuColumns struct {
Id string // 菜单ID
Pid string // 父菜单ID
Title string // 菜单名称
Name string // 名称编码
Path string // 路由地址
Icon string // 菜单图标
Type string // 菜单类型1目录 2菜单 3按钮
Redirect string // 重定向地址
Permissions string // 菜单包含权限集合
PermissionName string // 权限名称
Component string // 组件路径
AlwaysShow string // 取消自动计算根路由模式
ActiveMenu string // 高亮菜单编码
IsRoot string // 是否跟路由
IsFrame string // 是否内嵌
FrameSrc string // 内联外部地址
KeepAlive string // 缓存该路由
Hidden string // 是否隐藏
Affix string // 是否固定
Level string // 级别
Tree string // 树
Sort string // 排序
Remark string // 备注
Status string // 菜单状态
CreatedAt string // 创建时间
UpdatedAt string // 更新时间
}
// adminMenuColumns holds the columns for table hg_admin_menu.
var adminMenuColumns = AdminMenuColumns{
Id: "id",
Pid: "pid",
Title: "title",
Name: "name",
Path: "path",
Icon: "icon",
Type: "type",
Redirect: "redirect",
Permissions: "permissions",
PermissionName: "permission_name",
Component: "component",
AlwaysShow: "always_show",
ActiveMenu: "active_menu",
IsRoot: "is_root",
IsFrame: "is_frame",
FrameSrc: "frame_src",
KeepAlive: "keep_alive",
Hidden: "hidden",
Affix: "affix",
Level: "level",
Tree: "tree",
Sort: "sort",
Remark: "remark",
Status: "status",
CreatedAt: "created_at",
UpdatedAt: "updated_at",
}
// NewAdminMenuDao creates and returns a new DAO object for table data access.
func NewAdminMenuDao() *AdminMenuDao {
return &AdminMenuDao{
group: "default",
table: "hg_admin_menu",
columns: adminMenuColumns,
}
}
// DB retrieves and returns the underlying raw database management object of current DAO.
func (dao *AdminMenuDao) DB() gdb.DB {
return g.DB(dao.group)
}
// Table returns the table name of current dao.
func (dao *AdminMenuDao) Table() string {
return dao.table
}
// Columns returns all column names of current dao.
func (dao *AdminMenuDao) Columns() AdminMenuColumns {
return dao.columns
}
// Group returns the configuration group name of database of current dao.
func (dao *AdminMenuDao) Group() string {
return dao.group
}
// Ctx creates and returns the Model for current DAO, It automatically sets the context for current operation.
func (dao *AdminMenuDao) Ctx(ctx context.Context) *gdb.Model {
return dao.DB().Model(dao.table).Safe().Ctx(ctx)
}
// Transaction wraps the transaction logic using function f.
// It rollbacks the transaction and returns the error from function f if it returns non-nil error.
// It commits the transaction and returns nil if function f returns nil.
//
// Note that, you should not Commit or Rollback the transaction in function f
// as it is automatically handled by this function.
func (dao *AdminMenuDao) Transaction(ctx context.Context, f func(ctx context.Context, tx *gdb.TX) error) (err error) {
return dao.Ctx(ctx).Transaction(ctx, f)
}

View File

@@ -0,0 +1,93 @@
// ==========================================================================
// Code generated by GoFrame CLI tool. DO NOT EDIT.
// ==========================================================================
package internal
import (
"context"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
)
// AdminNoticeDao is the data access object for table hg_admin_notice.
type AdminNoticeDao struct {
table string // table is the underlying table name of the DAO.
group string // group is the database configuration group name of current DAO.
columns AdminNoticeColumns // columns contains all the column names of Table for convenient usage.
}
// AdminNoticeColumns defines and stores column names for table hg_admin_notice.
type AdminNoticeColumns struct {
Id string // 公告ID
Title string // 公告标题
Type string // 公告类型1通知 2公告
Content string // 公告内容
Receiver string // 接收者
Reader string // 已读人
Remark string // 备注
Sort string // 排序
Status string // 公告状态
CreatedAt string // 创建时间
UpdatedAt string // 更新时间
}
// adminNoticeColumns holds the columns for table hg_admin_notice.
var adminNoticeColumns = AdminNoticeColumns{
Id: "id",
Title: "title",
Type: "type",
Content: "content",
Receiver: "receiver",
Reader: "reader",
Remark: "remark",
Sort: "sort",
Status: "status",
CreatedAt: "created_at",
UpdatedAt: "updated_at",
}
// NewAdminNoticeDao creates and returns a new DAO object for table data access.
func NewAdminNoticeDao() *AdminNoticeDao {
return &AdminNoticeDao{
group: "default",
table: "hg_admin_notice",
columns: adminNoticeColumns,
}
}
// DB retrieves and returns the underlying raw database management object of current DAO.
func (dao *AdminNoticeDao) DB() gdb.DB {
return g.DB(dao.group)
}
// Table returns the table name of current dao.
func (dao *AdminNoticeDao) Table() string {
return dao.table
}
// Columns returns all column names of current dao.
func (dao *AdminNoticeDao) Columns() AdminNoticeColumns {
return dao.columns
}
// Group returns the configuration group name of database of current dao.
func (dao *AdminNoticeDao) Group() string {
return dao.group
}
// Ctx creates and returns the Model for current DAO, It automatically sets the context for current operation.
func (dao *AdminNoticeDao) Ctx(ctx context.Context) *gdb.Model {
return dao.DB().Model(dao.table).Safe().Ctx(ctx)
}
// Transaction wraps the transaction logic using function f.
// It rollbacks the transaction and returns the error from function f if it returns non-nil error.
// It commits the transaction and returns nil if function f returns nil.
//
// Note that, you should not Commit or Rollback the transaction in function f
// as it is automatically handled by this function.
func (dao *AdminNoticeDao) Transaction(ctx context.Context, f func(ctx context.Context, tx *gdb.TX) error) (err error) {
return dao.Ctx(ctx).Transaction(ctx, f)
}

View File

@@ -0,0 +1,87 @@
// ==========================================================================
// Code generated by GoFrame CLI tool. DO NOT EDIT.
// ==========================================================================
package internal
import (
"context"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
)
// AdminPostDao is the data access object for table hg_admin_post.
type AdminPostDao struct {
table string // table is the underlying table name of the DAO.
group string // group is the database configuration group name of current DAO.
columns AdminPostColumns // columns contains all the column names of Table for convenient usage.
}
// AdminPostColumns defines and stores column names for table hg_admin_post.
type AdminPostColumns struct {
Id string // 岗位ID
Code string // 岗位编码
Name string // 岗位名称
Remark string // 备注
Sort string // 显示顺序
Status string // 状态
CreatedAt string // 创建时间
UpdatedAt string // 更新时间
}
// adminPostColumns holds the columns for table hg_admin_post.
var adminPostColumns = AdminPostColumns{
Id: "id",
Code: "code",
Name: "name",
Remark: "remark",
Sort: "sort",
Status: "status",
CreatedAt: "created_at",
UpdatedAt: "updated_at",
}
// NewAdminPostDao creates and returns a new DAO object for table data access.
func NewAdminPostDao() *AdminPostDao {
return &AdminPostDao{
group: "default",
table: "hg_admin_post",
columns: adminPostColumns,
}
}
// DB retrieves and returns the underlying raw database management object of current DAO.
func (dao *AdminPostDao) DB() gdb.DB {
return g.DB(dao.group)
}
// Table returns the table name of current dao.
func (dao *AdminPostDao) Table() string {
return dao.table
}
// Columns returns all column names of current dao.
func (dao *AdminPostDao) Columns() AdminPostColumns {
return dao.columns
}
// Group returns the configuration group name of database of current dao.
func (dao *AdminPostDao) Group() string {
return dao.group
}
// Ctx creates and returns the Model for current DAO, It automatically sets the context for current operation.
func (dao *AdminPostDao) Ctx(ctx context.Context) *gdb.Model {
return dao.DB().Model(dao.table).Safe().Ctx(ctx)
}
// Transaction wraps the transaction logic using function f.
// It rollbacks the transaction and returns the error from function f if it returns non-nil error.
// It commits the transaction and returns nil if function f returns nil.
//
// Note that, you should not Commit or Rollback the transaction in function f
// as it is automatically handled by this function.
func (dao *AdminPostDao) Transaction(ctx context.Context, f func(ctx context.Context, tx *gdb.TX) error) (err error) {
return dao.Ctx(ctx).Transaction(ctx, f)
}

View File

@@ -0,0 +1,93 @@
// ==========================================================================
// Code generated by GoFrame CLI tool. DO NOT EDIT.
// ==========================================================================
package internal
import (
"context"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
)
// AdminRoleDao is the data access object for table hg_admin_role.
type AdminRoleDao struct {
table string // table is the underlying table name of the DAO.
group string // group is the database configuration group name of current DAO.
columns AdminRoleColumns // columns contains all the column names of Table for convenient usage.
}
// AdminRoleColumns defines and stores column names for table hg_admin_role.
type AdminRoleColumns struct {
Id string // 角色ID
Name string // 角色名称
Key string // 角色权限字符串
DataScope string // 数据范围1全部数据权限 2自定数据权限 3本部门数据权限 4本部门及以下数据权限
MenuCheckStrictly string // 菜单树选择项是否关联显示
DeptCheckStrictly string // 部门树选择项是否关联显示
Remark string // 备注
Sort string // 排序
Status string // 角色状态
CreatedAt string // 创建时间
UpdatedAt string // 更新时间
}
// adminRoleColumns holds the columns for table hg_admin_role.
var adminRoleColumns = AdminRoleColumns{
Id: "id",
Name: "name",
Key: "key",
DataScope: "data_scope",
MenuCheckStrictly: "menu_check_strictly",
DeptCheckStrictly: "dept_check_strictly",
Remark: "remark",
Sort: "sort",
Status: "status",
CreatedAt: "created_at",
UpdatedAt: "updated_at",
}
// NewAdminRoleDao creates and returns a new DAO object for table data access.
func NewAdminRoleDao() *AdminRoleDao {
return &AdminRoleDao{
group: "default",
table: "hg_admin_role",
columns: adminRoleColumns,
}
}
// DB retrieves and returns the underlying raw database management object of current DAO.
func (dao *AdminRoleDao) DB() gdb.DB {
return g.DB(dao.group)
}
// Table returns the table name of current dao.
func (dao *AdminRoleDao) Table() string {
return dao.table
}
// Columns returns all column names of current dao.
func (dao *AdminRoleDao) Columns() AdminRoleColumns {
return dao.columns
}
// Group returns the configuration group name of database of current dao.
func (dao *AdminRoleDao) Group() string {
return dao.group
}
// Ctx creates and returns the Model for current DAO, It automatically sets the context for current operation.
func (dao *AdminRoleDao) Ctx(ctx context.Context) *gdb.Model {
return dao.DB().Model(dao.table).Safe().Ctx(ctx)
}
// Transaction wraps the transaction logic using function f.
// It rollbacks the transaction and returns the error from function f if it returns non-nil error.
// It commits the transaction and returns nil if function f returns nil.
//
// Note that, you should not Commit or Rollback the transaction in function f
// as it is automatically handled by this function.
func (dao *AdminRoleDao) Transaction(ctx context.Context, f func(ctx context.Context, tx *gdb.TX) error) (err error) {
return dao.Ctx(ctx).Transaction(ctx, f)
}

View File

@@ -0,0 +1,87 @@
// ==========================================================================
// Code generated by GoFrame CLI tool. DO NOT EDIT.
// ==========================================================================
package internal
import (
"context"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
)
// AdminRoleCasbinDao is the data access object for table hg_admin_role_casbin.
type AdminRoleCasbinDao struct {
table string // table is the underlying table name of the DAO.
group string // group is the database configuration group name of current DAO.
columns AdminRoleCasbinColumns // columns contains all the column names of Table for convenient usage.
}
// AdminRoleCasbinColumns defines and stores column names for table hg_admin_role_casbin.
type AdminRoleCasbinColumns struct {
Id string //
PType string //
V0 string //
V1 string //
V2 string //
V3 string //
V4 string //
V5 string //
}
// adminRoleCasbinColumns holds the columns for table hg_admin_role_casbin.
var adminRoleCasbinColumns = AdminRoleCasbinColumns{
Id: "id",
PType: "p_type",
V0: "v0",
V1: "v1",
V2: "v2",
V3: "v3",
V4: "v4",
V5: "v5",
}
// NewAdminRoleCasbinDao creates and returns a new DAO object for table data access.
func NewAdminRoleCasbinDao() *AdminRoleCasbinDao {
return &AdminRoleCasbinDao{
group: "default",
table: "hg_admin_role_casbin",
columns: adminRoleCasbinColumns,
}
}
// DB retrieves and returns the underlying raw database management object of current DAO.
func (dao *AdminRoleCasbinDao) DB() gdb.DB {
return g.DB(dao.group)
}
// Table returns the table name of current dao.
func (dao *AdminRoleCasbinDao) Table() string {
return dao.table
}
// Columns returns all column names of current dao.
func (dao *AdminRoleCasbinDao) Columns() AdminRoleCasbinColumns {
return dao.columns
}
// Group returns the configuration group name of database of current dao.
func (dao *AdminRoleCasbinDao) Group() string {
return dao.group
}
// Ctx creates and returns the Model for current DAO, It automatically sets the context for current operation.
func (dao *AdminRoleCasbinDao) Ctx(ctx context.Context) *gdb.Model {
return dao.DB().Model(dao.table).Safe().Ctx(ctx)
}
// Transaction wraps the transaction logic using function f.
// It rollbacks the transaction and returns the error from function f if it returns non-nil error.
// It commits the transaction and returns nil if function f returns nil.
//
// Note that, you should not Commit or Rollback the transaction in function f
// as it is automatically handled by this function.
func (dao *AdminRoleCasbinDao) Transaction(ctx context.Context, f func(ctx context.Context, tx *gdb.TX) error) (err error) {
return dao.Ctx(ctx).Transaction(ctx, f)
}

View File

@@ -0,0 +1,75 @@
// ==========================================================================
// Code generated by GoFrame CLI tool. DO NOT EDIT.
// ==========================================================================
package internal
import (
"context"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
)
// AdminRoleDeptDao is the data access object for table hg_admin_role_dept.
type AdminRoleDeptDao struct {
table string // table is the underlying table name of the DAO.
group string // group is the database configuration group name of current DAO.
columns AdminRoleDeptColumns // columns contains all the column names of Table for convenient usage.
}
// AdminRoleDeptColumns defines and stores column names for table hg_admin_role_dept.
type AdminRoleDeptColumns struct {
RoleId string // 角色ID
DeptId string // 部门ID
}
// adminRoleDeptColumns holds the columns for table hg_admin_role_dept.
var adminRoleDeptColumns = AdminRoleDeptColumns{
RoleId: "role_id",
DeptId: "dept_id",
}
// NewAdminRoleDeptDao creates and returns a new DAO object for table data access.
func NewAdminRoleDeptDao() *AdminRoleDeptDao {
return &AdminRoleDeptDao{
group: "default",
table: "hg_admin_role_dept",
columns: adminRoleDeptColumns,
}
}
// DB retrieves and returns the underlying raw database management object of current DAO.
func (dao *AdminRoleDeptDao) DB() gdb.DB {
return g.DB(dao.group)
}
// Table returns the table name of current dao.
func (dao *AdminRoleDeptDao) Table() string {
return dao.table
}
// Columns returns all column names of current dao.
func (dao *AdminRoleDeptDao) Columns() AdminRoleDeptColumns {
return dao.columns
}
// Group returns the configuration group name of database of current dao.
func (dao *AdminRoleDeptDao) Group() string {
return dao.group
}
// Ctx creates and returns the Model for current DAO, It automatically sets the context for current operation.
func (dao *AdminRoleDeptDao) Ctx(ctx context.Context) *gdb.Model {
return dao.DB().Model(dao.table).Safe().Ctx(ctx)
}
// Transaction wraps the transaction logic using function f.
// It rollbacks the transaction and returns the error from function f if it returns non-nil error.
// It commits the transaction and returns nil if function f returns nil.
//
// Note that, you should not Commit or Rollback the transaction in function f
// as it is automatically handled by this function.
func (dao *AdminRoleDeptDao) Transaction(ctx context.Context, f func(ctx context.Context, tx *gdb.TX) error) (err error) {
return dao.Ctx(ctx).Transaction(ctx, f)
}

View File

@@ -0,0 +1,75 @@
// ==========================================================================
// Code generated by GoFrame CLI tool. DO NOT EDIT.
// ==========================================================================
package internal
import (
"context"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
)
// AdminRoleMenuDao is the data access object for table hg_admin_role_menu.
type AdminRoleMenuDao struct {
table string // table is the underlying table name of the DAO.
group string // group is the database configuration group name of current DAO.
columns AdminRoleMenuColumns // columns contains all the column names of Table for convenient usage.
}
// AdminRoleMenuColumns defines and stores column names for table hg_admin_role_menu.
type AdminRoleMenuColumns struct {
RoleId string // 角色ID
MenuId string // 菜单ID
}
// adminRoleMenuColumns holds the columns for table hg_admin_role_menu.
var adminRoleMenuColumns = AdminRoleMenuColumns{
RoleId: "role_id",
MenuId: "menu_id",
}
// NewAdminRoleMenuDao creates and returns a new DAO object for table data access.
func NewAdminRoleMenuDao() *AdminRoleMenuDao {
return &AdminRoleMenuDao{
group: "default",
table: "hg_admin_role_menu",
columns: adminRoleMenuColumns,
}
}
// DB retrieves and returns the underlying raw database management object of current DAO.
func (dao *AdminRoleMenuDao) DB() gdb.DB {
return g.DB(dao.group)
}
// Table returns the table name of current dao.
func (dao *AdminRoleMenuDao) Table() string {
return dao.table
}
// Columns returns all column names of current dao.
func (dao *AdminRoleMenuDao) Columns() AdminRoleMenuColumns {
return dao.columns
}
// Group returns the configuration group name of database of current dao.
func (dao *AdminRoleMenuDao) Group() string {
return dao.group
}
// Ctx creates and returns the Model for current DAO, It automatically sets the context for current operation.
func (dao *AdminRoleMenuDao) Ctx(ctx context.Context) *gdb.Model {
return dao.DB().Model(dao.table).Safe().Ctx(ctx)
}
// Transaction wraps the transaction logic using function f.
// It rollbacks the transaction and returns the error from function f if it returns non-nil error.
// It commits the transaction and returns nil if function f returns nil.
//
// Note that, you should not Commit or Rollback the transaction in function f
// as it is automatically handled by this function.
func (dao *AdminRoleMenuDao) Transaction(ctx context.Context, f func(ctx context.Context, tx *gdb.TX) error) (err error) {
return dao.Ctx(ctx).Transaction(ctx, f)
}

View File

@@ -0,0 +1,105 @@
// ==========================================================================
// Code generated by GoFrame CLI tool. DO NOT EDIT.
// ==========================================================================
package internal
import (
"context"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
)
// SysAttachmentDao is the data access object for table hg_sys_attachment.
type SysAttachmentDao struct {
table string // table is the underlying table name of the DAO.
group string // group is the database configuration group name of current DAO.
columns SysAttachmentColumns // columns contains all the column names of Table for convenient usage.
}
// SysAttachmentColumns defines and stores column names for table hg_sys_attachment.
type SysAttachmentColumns struct {
Id string //
AppId string // 应用ID
MemberId string // 用户
CateId string // 分类
Drive string // 驱动
Name string // 文件原始名
Kind string // 上传类型
MetaType string // 类别
NaiveType string // NaiveUI类型
Path string // 本地路径
FileUrl string // url
Size string // 长度
Ext string // 扩展名
Md5 string // md5校验码
Status string // 状态
CreatedAt string // 创建时间
UpdatedAt string // 修改时间
}
// sysAttachmentColumns holds the columns for table hg_sys_attachment.
var sysAttachmentColumns = SysAttachmentColumns{
Id: "id",
AppId: "app_id",
MemberId: "member_id",
CateId: "cate_id",
Drive: "drive",
Name: "name",
Kind: "kind",
MetaType: "meta_type",
NaiveType: "naive_type",
Path: "path",
FileUrl: "file_url",
Size: "size",
Ext: "ext",
Md5: "md5",
Status: "status",
CreatedAt: "created_at",
UpdatedAt: "updated_at",
}
// NewSysAttachmentDao creates and returns a new DAO object for table data access.
func NewSysAttachmentDao() *SysAttachmentDao {
return &SysAttachmentDao{
group: "default",
table: "hg_sys_attachment",
columns: sysAttachmentColumns,
}
}
// DB retrieves and returns the underlying raw database management object of current DAO.
func (dao *SysAttachmentDao) DB() gdb.DB {
return g.DB(dao.group)
}
// Table returns the table name of current dao.
func (dao *SysAttachmentDao) Table() string {
return dao.table
}
// Columns returns all column names of current dao.
func (dao *SysAttachmentDao) Columns() SysAttachmentColumns {
return dao.columns
}
// Group returns the configuration group name of database of current dao.
func (dao *SysAttachmentDao) Group() string {
return dao.group
}
// Ctx creates and returns the Model for current DAO, It automatically sets the context for current operation.
func (dao *SysAttachmentDao) Ctx(ctx context.Context) *gdb.Model {
return dao.DB().Model(dao.table).Safe().Ctx(ctx)
}
// Transaction wraps the transaction logic using function f.
// It rollbacks the transaction and returns the error from function f if it returns non-nil error.
// It commits the transaction and returns nil if function f returns nil.
//
// Note that, you should not Commit or Rollback the transaction in function f
// as it is automatically handled by this function.
func (dao *SysAttachmentDao) Transaction(ctx context.Context, f func(ctx context.Context, tx *gdb.TX) error) (err error) {
return dao.Ctx(ctx).Transaction(ctx, f)
}

View File

@@ -0,0 +1,83 @@
// ==========================================================================
// Code generated by GoFrame CLI tool. DO NOT EDIT.
// ==========================================================================
package internal
import (
"context"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
)
// SysBlacklistDao is the data access object for table hg_sys_blacklist.
type SysBlacklistDao struct {
table string // table is the underlying table name of the DAO.
group string // group is the database configuration group name of current DAO.
columns SysBlacklistColumns // columns contains all the column names of Table for convenient usage.
}
// SysBlacklistColumns defines and stores column names for table hg_sys_blacklist.
type SysBlacklistColumns struct {
Id string // 主键
Ip string // ip地址
Remark string // 备注
Status string // 状态
CreatedAt string // 创建时间
UpdatedAt string // 更新时间
}
// sysBlacklistColumns holds the columns for table hg_sys_blacklist.
var sysBlacklistColumns = SysBlacklistColumns{
Id: "id",
Ip: "ip",
Remark: "remark",
Status: "status",
CreatedAt: "created_at",
UpdatedAt: "updated_at",
}
// NewSysBlacklistDao creates and returns a new DAO object for table data access.
func NewSysBlacklistDao() *SysBlacklistDao {
return &SysBlacklistDao{
group: "default",
table: "hg_sys_blacklist",
columns: sysBlacklistColumns,
}
}
// DB retrieves and returns the underlying raw database management object of current DAO.
func (dao *SysBlacklistDao) DB() gdb.DB {
return g.DB(dao.group)
}
// Table returns the table name of current dao.
func (dao *SysBlacklistDao) Table() string {
return dao.table
}
// Columns returns all column names of current dao.
func (dao *SysBlacklistDao) Columns() SysBlacklistColumns {
return dao.columns
}
// Group returns the configuration group name of database of current dao.
func (dao *SysBlacklistDao) Group() string {
return dao.group
}
// Ctx creates and returns the Model for current DAO, It automatically sets the context for current operation.
func (dao *SysBlacklistDao) Ctx(ctx context.Context) *gdb.Model {
return dao.DB().Model(dao.table).Safe().Ctx(ctx)
}
// Transaction wraps the transaction logic using function f.
// It rollbacks the transaction and returns the error from function f if it returns non-nil error.
// It commits the transaction and returns nil if function f returns nil.
//
// Note that, you should not Commit or Rollback the transaction in function f
// as it is automatically handled by this function.
func (dao *SysBlacklistDao) Transaction(ctx context.Context, f func(ctx context.Context, tx *gdb.TX) error) (err error) {
return dao.Ctx(ctx).Transaction(ctx, f)
}

View File

@@ -0,0 +1,97 @@
// ==========================================================================
// Code generated by GoFrame CLI tool. DO NOT EDIT.
// ==========================================================================
package internal
import (
"context"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
)
// SysConfigDao is the data access object for table hg_sys_config.
type SysConfigDao struct {
table string // table is the underlying table name of the DAO.
group string // group is the database configuration group name of current DAO.
columns SysConfigColumns // columns contains all the column names of Table for convenient usage.
}
// SysConfigColumns defines and stores column names for table hg_sys_config.
type SysConfigColumns struct {
Id string // 配置ID
Group string // 分组
Name string // 参数名称
Type string // 类型:string,text,int,bool,array,datetime,date,file
Key string // 参数键名
Value string // 参数键值
DefaultValue string // 默认值
Sort string // 排序
Tip string // 变量描述
IsDefault string // 是否默认
Status string // 状态
CreatedAt string // 创建时间
UpdatedAt string // 更新时间
}
// sysConfigColumns holds the columns for table hg_sys_config.
var sysConfigColumns = SysConfigColumns{
Id: "id",
Group: "group",
Name: "name",
Type: "type",
Key: "key",
Value: "value",
DefaultValue: "default_value",
Sort: "sort",
Tip: "tip",
IsDefault: "is_default",
Status: "status",
CreatedAt: "created_at",
UpdatedAt: "updated_at",
}
// NewSysConfigDao creates and returns a new DAO object for table data access.
func NewSysConfigDao() *SysConfigDao {
return &SysConfigDao{
group: "default",
table: "hg_sys_config",
columns: sysConfigColumns,
}
}
// DB retrieves and returns the underlying raw database management object of current DAO.
func (dao *SysConfigDao) DB() gdb.DB {
return g.DB(dao.group)
}
// Table returns the table name of current dao.
func (dao *SysConfigDao) Table() string {
return dao.table
}
// Columns returns all column names of current dao.
func (dao *SysConfigDao) Columns() SysConfigColumns {
return dao.columns
}
// Group returns the configuration group name of database of current dao.
func (dao *SysConfigDao) Group() string {
return dao.group
}
// Ctx creates and returns the Model for current DAO, It automatically sets the context for current operation.
func (dao *SysConfigDao) Ctx(ctx context.Context) *gdb.Model {
return dao.DB().Model(dao.table).Safe().Ctx(ctx)
}
// Transaction wraps the transaction logic using function f.
// It rollbacks the transaction and returns the error from function f if it returns non-nil error.
// It commits the transaction and returns nil if function f returns nil.
//
// Note that, you should not Commit or Rollback the transaction in function f
// as it is automatically handled by this function.
func (dao *SysConfigDao) Transaction(ctx context.Context, f func(ctx context.Context, tx *gdb.TX) error) (err error) {
return dao.Ctx(ctx).Transaction(ctx, f)
}

View File

@@ -0,0 +1,95 @@
// ==========================================================================
// Code generated by GoFrame CLI tool. DO NOT EDIT.
// ==========================================================================
package internal
import (
"context"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
)
// SysCronDao is the data access object for table hg_sys_cron.
type SysCronDao struct {
table string // table is the underlying table name of the DAO.
group string // group is the database configuration group name of current DAO.
columns SysCronColumns // columns contains all the column names of Table for convenient usage.
}
// SysCronColumns defines and stores column names for table hg_sys_cron.
type SysCronColumns struct {
Id string // 主键
GroupId string // 分组ID
Name string // 任务名称
Params string // 函数参数
Pattern string // 定时表达式
Policy string // 策略
Count string // 执行次数
Sort string // 排序
Remark string // 备注
Status string // 状态
CreatedAt string // 创建时间
UpdatedAt string // 更新时间
}
// sysCronColumns holds the columns for table hg_sys_cron.
var sysCronColumns = SysCronColumns{
Id: "id",
GroupId: "group_id",
Name: "name",
Params: "params",
Pattern: "pattern",
Policy: "policy",
Count: "count",
Sort: "sort",
Remark: "remark",
Status: "status",
CreatedAt: "created_at",
UpdatedAt: "updated_at",
}
// NewSysCronDao creates and returns a new DAO object for table data access.
func NewSysCronDao() *SysCronDao {
return &SysCronDao{
group: "default",
table: "hg_sys_cron",
columns: sysCronColumns,
}
}
// DB retrieves and returns the underlying raw database management object of current DAO.
func (dao *SysCronDao) DB() gdb.DB {
return g.DB(dao.group)
}
// Table returns the table name of current dao.
func (dao *SysCronDao) Table() string {
return dao.table
}
// Columns returns all column names of current dao.
func (dao *SysCronDao) Columns() SysCronColumns {
return dao.columns
}
// Group returns the configuration group name of database of current dao.
func (dao *SysCronDao) Group() string {
return dao.group
}
// Ctx creates and returns the Model for current DAO, It automatically sets the context for current operation.
func (dao *SysCronDao) Ctx(ctx context.Context) *gdb.Model {
return dao.DB().Model(dao.table).Safe().Ctx(ctx)
}
// Transaction wraps the transaction logic using function f.
// It rollbacks the transaction and returns the error from function f if it returns non-nil error.
// It commits the transaction and returns nil if function f returns nil.
//
// Note that, you should not Commit or Rollback the transaction in function f
// as it is automatically handled by this function.
func (dao *SysCronDao) Transaction(ctx context.Context, f func(ctx context.Context, tx *gdb.TX) error) (err error) {
return dao.Ctx(ctx).Transaction(ctx, f)
}

View File

@@ -0,0 +1,89 @@
// ==========================================================================
// Code generated by GoFrame CLI tool. DO NOT EDIT.
// ==========================================================================
package internal
import (
"context"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
)
// SysCronGroupDao is the data access object for table hg_sys_cron_group.
type SysCronGroupDao struct {
table string // table is the underlying table name of the DAO.
group string // group is the database configuration group name of current DAO.
columns SysCronGroupColumns // columns contains all the column names of Table for convenient usage.
}
// SysCronGroupColumns defines and stores column names for table hg_sys_cron_group.
type SysCronGroupColumns struct {
Id string // 主键
Pid string // 父类ID
Name string // 分组名称
IsDefault string // 是否默认
Sort string // 排序
Remark string // 备注
Status string // 状态
CreatedAt string // 创建时间
UpdatedAt string // 更新时间
}
// sysCronGroupColumns holds the columns for table hg_sys_cron_group.
var sysCronGroupColumns = SysCronGroupColumns{
Id: "id",
Pid: "pid",
Name: "name",
IsDefault: "is_default",
Sort: "sort",
Remark: "remark",
Status: "status",
CreatedAt: "created_at",
UpdatedAt: "updated_at",
}
// NewSysCronGroupDao creates and returns a new DAO object for table data access.
func NewSysCronGroupDao() *SysCronGroupDao {
return &SysCronGroupDao{
group: "default",
table: "hg_sys_cron_group",
columns: sysCronGroupColumns,
}
}
// DB retrieves and returns the underlying raw database management object of current DAO.
func (dao *SysCronGroupDao) DB() gdb.DB {
return g.DB(dao.group)
}
// Table returns the table name of current dao.
func (dao *SysCronGroupDao) Table() string {
return dao.table
}
// Columns returns all column names of current dao.
func (dao *SysCronGroupDao) Columns() SysCronGroupColumns {
return dao.columns
}
// Group returns the configuration group name of database of current dao.
func (dao *SysCronGroupDao) Group() string {
return dao.group
}
// Ctx creates and returns the Model for current DAO, It automatically sets the context for current operation.
func (dao *SysCronGroupDao) Ctx(ctx context.Context) *gdb.Model {
return dao.DB().Model(dao.table).Safe().Ctx(ctx)
}
// Transaction wraps the transaction logic using function f.
// It rollbacks the transaction and returns the error from function f if it returns non-nil error.
// It commits the transaction and returns nil if function f returns nil.
//
// Note that, you should not Commit or Rollback the transaction in function f
// as it is automatically handled by this function.
func (dao *SysCronGroupDao) Transaction(ctx context.Context, f func(ctx context.Context, tx *gdb.TX) error) (err error) {
return dao.Ctx(ctx).Transaction(ctx, f)
}

View File

@@ -0,0 +1,93 @@
// ==========================================================================
// Code generated by GoFrame CLI tool. DO NOT EDIT.
// ==========================================================================
package internal
import (
"context"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
)
// SysDictDataDao is the data access object for table hg_sys_dict_data.
type SysDictDataDao struct {
table string // table is the underlying table name of the DAO.
group string // group is the database configuration group name of current DAO.
columns SysDictDataColumns // columns contains all the column names of Table for convenient usage.
}
// SysDictDataColumns defines and stores column names for table hg_sys_dict_data.
type SysDictDataColumns struct {
Id string // 字典编码
Label string // 字典标签
Value string // 字典键值
Type string // 字典类型
ListClass string // 表格回显样式
IsDefault string // 是否默认
Sort string // 字典排序
Remark string // 备注
Status string // 状态
CreatedAt string // 创建时间
UpdatedAt string // 更新时间
}
// sysDictDataColumns holds the columns for table hg_sys_dict_data.
var sysDictDataColumns = SysDictDataColumns{
Id: "id",
Label: "label",
Value: "value",
Type: "type",
ListClass: "list_class",
IsDefault: "is_default",
Sort: "sort",
Remark: "remark",
Status: "status",
CreatedAt: "created_at",
UpdatedAt: "updated_at",
}
// NewSysDictDataDao creates and returns a new DAO object for table data access.
func NewSysDictDataDao() *SysDictDataDao {
return &SysDictDataDao{
group: "default",
table: "hg_sys_dict_data",
columns: sysDictDataColumns,
}
}
// DB retrieves and returns the underlying raw database management object of current DAO.
func (dao *SysDictDataDao) DB() gdb.DB {
return g.DB(dao.group)
}
// Table returns the table name of current dao.
func (dao *SysDictDataDao) Table() string {
return dao.table
}
// Columns returns all column names of current dao.
func (dao *SysDictDataDao) Columns() SysDictDataColumns {
return dao.columns
}
// Group returns the configuration group name of database of current dao.
func (dao *SysDictDataDao) Group() string {
return dao.group
}
// Ctx creates and returns the Model for current DAO, It automatically sets the context for current operation.
func (dao *SysDictDataDao) Ctx(ctx context.Context) *gdb.Model {
return dao.DB().Model(dao.table).Safe().Ctx(ctx)
}
// Transaction wraps the transaction logic using function f.
// It rollbacks the transaction and returns the error from function f if it returns non-nil error.
// It commits the transaction and returns nil if function f returns nil.
//
// Note that, you should not Commit or Rollback the transaction in function f
// as it is automatically handled by this function.
func (dao *SysDictDataDao) Transaction(ctx context.Context, f func(ctx context.Context, tx *gdb.TX) error) (err error) {
return dao.Ctx(ctx).Transaction(ctx, f)
}

View File

@@ -0,0 +1,89 @@
// ==========================================================================
// Code generated by GoFrame CLI tool. DO NOT EDIT.
// ==========================================================================
package internal
import (
"context"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
)
// SysDictTypeDao is the data access object for table hg_sys_dict_type.
type SysDictTypeDao struct {
table string // table is the underlying table name of the DAO.
group string // group is the database configuration group name of current DAO.
columns SysDictTypeColumns // columns contains all the column names of Table for convenient usage.
}
// SysDictTypeColumns defines and stores column names for table hg_sys_dict_type.
type SysDictTypeColumns struct {
Id string // 字典主键
Pid string // 父类ID
Name string // 字典名称
Type string // 字典类型
Sort string // 排序
Remark string // 备注
Status string // 状态
CreatedAt string // 创建时间
UpdatedAt string // 更新时间
}
// sysDictTypeColumns holds the columns for table hg_sys_dict_type.
var sysDictTypeColumns = SysDictTypeColumns{
Id: "id",
Pid: "pid",
Name: "name",
Type: "type",
Sort: "sort",
Remark: "remark",
Status: "status",
CreatedAt: "created_at",
UpdatedAt: "updated_at",
}
// NewSysDictTypeDao creates and returns a new DAO object for table data access.
func NewSysDictTypeDao() *SysDictTypeDao {
return &SysDictTypeDao{
group: "default",
table: "hg_sys_dict_type",
columns: sysDictTypeColumns,
}
}
// DB retrieves and returns the underlying raw database management object of current DAO.
func (dao *SysDictTypeDao) DB() gdb.DB {
return g.DB(dao.group)
}
// Table returns the table name of current dao.
func (dao *SysDictTypeDao) Table() string {
return dao.table
}
// Columns returns all column names of current dao.
func (dao *SysDictTypeDao) Columns() SysDictTypeColumns {
return dao.columns
}
// Group returns the configuration group name of database of current dao.
func (dao *SysDictTypeDao) Group() string {
return dao.group
}
// Ctx creates and returns the Model for current DAO, It automatically sets the context for current operation.
func (dao *SysDictTypeDao) Ctx(ctx context.Context) *gdb.Model {
return dao.DB().Model(dao.table).Safe().Ctx(ctx)
}
// Transaction wraps the transaction logic using function f.
// It rollbacks the transaction and returns the error from function f if it returns non-nil error.
// It commits the transaction and returns nil if function f returns nil.
//
// Note that, you should not Commit or Rollback the transaction in function f
// as it is automatically handled by this function.
func (dao *SysDictTypeDao) Transaction(ctx context.Context, f func(ctx context.Context, tx *gdb.TX) error) (err error) {
return dao.Ctx(ctx).Transaction(ctx, f)
}

View File

@@ -0,0 +1,117 @@
// ==========================================================================
// Code generated by GoFrame CLI tool. DO NOT EDIT.
// ==========================================================================
package internal
import (
"context"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
)
// SysLogDao is the data access object for table hg_sys_log.
type SysLogDao struct {
table string // table is the underlying table name of the DAO.
group string // group is the database configuration group name of current DAO.
columns SysLogColumns // columns contains all the column names of Table for convenient usage.
}
// SysLogColumns defines and stores column names for table hg_sys_log.
type SysLogColumns struct {
Id string //
AppId string // 应用id
MerchantId string // 商户id
MemberId string // 用户id
Method string // 提交类型
Module string // 模块
Url string // 提交url
GetData string // get数据
PostData string // post数据
HeaderData string // header数据
Ip string // ip地址
ProvinceId string // 省编码
CityId string // 市编码
ErrorCode string // 报错code
ErrorMsg string // 报错信息
ErrorData string // 报错日志
ReqId string // 对外id
Timestamp string // 响应时间
UserAgent string // UA信息
TakeUpTime string // 请求耗时
Status string // 状态
CreatedAt string // 创建时间
UpdatedAt string // 修改时间
}
// sysLogColumns holds the columns for table hg_sys_log.
var sysLogColumns = SysLogColumns{
Id: "id",
AppId: "app_id",
MerchantId: "merchant_id",
MemberId: "member_id",
Method: "method",
Module: "module",
Url: "url",
GetData: "get_data",
PostData: "post_data",
HeaderData: "header_data",
Ip: "ip",
ProvinceId: "province_id",
CityId: "city_id",
ErrorCode: "error_code",
ErrorMsg: "error_msg",
ErrorData: "error_data",
ReqId: "req_id",
Timestamp: "timestamp",
UserAgent: "user_agent",
TakeUpTime: "take_up_time",
Status: "status",
CreatedAt: "created_at",
UpdatedAt: "updated_at",
}
// NewSysLogDao creates and returns a new DAO object for table data access.
func NewSysLogDao() *SysLogDao {
return &SysLogDao{
group: "default",
table: "hg_sys_log",
columns: sysLogColumns,
}
}
// DB retrieves and returns the underlying raw database management object of current DAO.
func (dao *SysLogDao) DB() gdb.DB {
return g.DB(dao.group)
}
// Table returns the table name of current dao.
func (dao *SysLogDao) Table() string {
return dao.table
}
// Columns returns all column names of current dao.
func (dao *SysLogDao) Columns() SysLogColumns {
return dao.columns
}
// Group returns the configuration group name of database of current dao.
func (dao *SysLogDao) Group() string {
return dao.group
}
// Ctx creates and returns the Model for current DAO, It automatically sets the context for current operation.
func (dao *SysLogDao) Ctx(ctx context.Context) *gdb.Model {
return dao.DB().Model(dao.table).Safe().Ctx(ctx)
}
// Transaction wraps the transaction logic using function f.
// It rollbacks the transaction and returns the error from function f if it returns non-nil error.
// It commits the transaction and returns nil if function f returns nil.
//
// Note that, you should not Commit or Rollback the transaction in function f
// as it is automatically handled by this function.
func (dao *SysLogDao) Transaction(ctx context.Context, f func(ctx context.Context, tx *gdb.TX) error) (err error) {
return dao.Ctx(ctx).Transaction(ctx, f)
}

View File

@@ -0,0 +1,101 @@
// ==========================================================================
// Code generated by GoFrame CLI tool. DO NOT EDIT.
// ==========================================================================
package internal
import (
"context"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
)
// SysProvincesDao is the data access object for table hg_sys_provinces.
type SysProvincesDao struct {
table string // table is the underlying table name of the DAO.
group string // group is the database configuration group name of current DAO.
columns SysProvincesColumns // columns contains all the column names of Table for convenient usage.
}
// SysProvincesColumns defines and stores column names for table hg_sys_provinces.
type SysProvincesColumns struct {
Id string // ID
Title string // 栏目名
Pid string // 父栏目
ShortTitle string // 缩写
Areacode string // 区域编码
Zipcode string // 邮政编码
Pinyin string // 拼音
Lng string // 经度
Lat string // 纬度
Level string // 级别
Tree string //
Sort string // 排序
Status string // 状态
CreatedAt string // 创建时间
UpdatedAt string // 更新时间
}
// sysProvincesColumns holds the columns for table hg_sys_provinces.
var sysProvincesColumns = SysProvincesColumns{
Id: "id",
Title: "title",
Pid: "pid",
ShortTitle: "short_title",
Areacode: "areacode",
Zipcode: "zipcode",
Pinyin: "pinyin",
Lng: "lng",
Lat: "lat",
Level: "level",
Tree: "tree",
Sort: "sort",
Status: "status",
CreatedAt: "created_at",
UpdatedAt: "updated_at",
}
// NewSysProvincesDao creates and returns a new DAO object for table data access.
func NewSysProvincesDao() *SysProvincesDao {
return &SysProvincesDao{
group: "default",
table: "hg_sys_provinces",
columns: sysProvincesColumns,
}
}
// DB retrieves and returns the underlying raw database management object of current DAO.
func (dao *SysProvincesDao) DB() gdb.DB {
return g.DB(dao.group)
}
// Table returns the table name of current dao.
func (dao *SysProvincesDao) Table() string {
return dao.table
}
// Columns returns all column names of current dao.
func (dao *SysProvincesDao) Columns() SysProvincesColumns {
return dao.columns
}
// Group returns the configuration group name of database of current dao.
func (dao *SysProvincesDao) Group() string {
return dao.group
}
// Ctx creates and returns the Model for current DAO, It automatically sets the context for current operation.
func (dao *SysProvincesDao) Ctx(ctx context.Context) *gdb.Model {
return dao.DB().Model(dao.table).Safe().Ctx(ctx)
}
// Transaction wraps the transaction logic using function f.
// It rollbacks the transaction and returns the error from function f if it returns non-nil error.
// It commits the transaction and returns nil if function f returns nil.
//
// Note that, you should not Commit or Rollback the transaction in function f
// as it is automatically handled by this function.
func (dao *SysProvincesDao) Transaction(ctx context.Context, f func(ctx context.Context, tx *gdb.TX) error) (err error) {
return dao.Ctx(ctx).Transaction(ctx, f)
}

View File

@@ -0,0 +1,51 @@
// =================================================================================
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
// =================================================================================
package dao
import (
"context"
"github.com/gogf/gf/v2/errors/gerror"
"hotgo/internal/consts"
"hotgo/internal/dao/internal"
"hotgo/internal/model/input/sysin"
"hotgo/internal/service"
"hotgo/utility/format"
)
// internalSysAttachmentDao is internal type for wrapping internal DAO implements.
type internalSysAttachmentDao = *internal.SysAttachmentDao
// sysAttachmentDao is the data access object for table hg_sys_attachment.
// You can define custom methods on it to extend its functionality as you wish.
type sysAttachmentDao struct {
internalSysAttachmentDao
}
var (
// SysAttachment is globally public accessible object for table hg_sys_attachment operations.
SysAttachment = sysAttachmentDao{
internal.NewSysAttachmentDao(),
}
)
func (dao *sysAttachmentDao) GetMd5File(ctx context.Context, md5 string) (data *sysin.AttachmentListModel, err error) {
if err = dao.Ctx(ctx).
Where("md5", md5).
Where("status", consts.StatusEnabled).
Scan(&data); err != nil {
err = gerror.Wrap(err, consts.ErrorORM)
return nil, err
}
if data == nil {
return nil, nil
}
data.SizeFormat = format.FileSize(data.Size)
data.FileUrl = service.CommonUpload().LastUrl(ctx, data.FileUrl, data.Drive)
return data, nil
}

View File

@@ -0,0 +1,27 @@
// =================================================================================
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
// =================================================================================
package dao
import (
"hotgo/internal/dao/internal"
)
// internalSysBlacklistDao is internal type for wrapping internal DAO implements.
type internalSysBlacklistDao = *internal.SysBlacklistDao
// sysBlacklistDao is the data access object for table hg_sys_blacklist.
// You can define custom methods on it to extend its functionality as you wish.
type sysBlacklistDao struct {
internalSysBlacklistDao
}
var (
// SysBlacklist is globally public accessible object for table hg_sys_blacklist operations.
SysBlacklist = sysBlacklistDao{
internal.NewSysBlacklistDao(),
}
)
// Fill with you ideas below.

View File

@@ -0,0 +1,27 @@
// =================================================================================
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
// =================================================================================
package dao
import (
"hotgo/internal/dao/internal"
)
// internalSysConfigDao is internal type for wrapping internal DAO implements.
type internalSysConfigDao = *internal.SysConfigDao
// sysConfigDao is the data access object for table hg_sys_config.
// You can define custom methods on it to extend its functionality as you wish.
type sysConfigDao struct {
internalSysConfigDao
}
var (
// SysConfig is globally common accessible object for table hg_sys_config operations.
SysConfig = sysConfigDao{
internal.NewSysConfigDao(),
}
)
// Fill with you ideas below.

View File

@@ -0,0 +1,27 @@
// =================================================================================
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
// =================================================================================
package dao
import (
"hotgo/internal/dao/internal"
)
// internalSysCronDao is internal type for wrapping internal DAO implements.
type internalSysCronDao = *internal.SysCronDao
// sysCronDao is the data access object for table hg_sys_cron.
// You can define custom methods on it to extend its functionality as you wish.
type sysCronDao struct {
internalSysCronDao
}
var (
// SysCron is globally public accessible object for table hg_sys_cron operations.
SysCron = sysCronDao{
internal.NewSysCronDao(),
}
)
// Fill with you ideas below.

View File

@@ -0,0 +1,40 @@
// =================================================================================
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
// =================================================================================
package dao
import (
"context"
"github.com/gogf/gf/v2/errors/gerror"
"hotgo/internal/consts"
"hotgo/internal/dao/internal"
)
// internalSysCronGroupDao is internal type for wrapping internal DAO implements.
type internalSysCronGroupDao = *internal.SysCronGroupDao
// sysCronGroupDao is the data access object for table hg_sys_cron_group.
// You can define custom methods on it to extend its functionality as you wish.
type sysCronGroupDao struct {
internalSysCronGroupDao
}
var (
// SysCronGroup is globally public accessible object for table hg_sys_cron_group operations.
SysCronGroup = sysCronGroupDao{
internal.NewSysCronGroupDao(),
}
)
// GetName 获取分组名称
func (dao *sysCronGroupDao) GetName(ctx context.Context, id int64) (name string, err error) {
m := dao.Ctx(ctx).Fields("name").Where("id", id)
list, err := m.Value()
if err != nil {
err = gerror.Wrap(err, consts.ErrorORM)
return name, err
}
return list.String(), nil
}

View File

@@ -0,0 +1,27 @@
// =================================================================================
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
// =================================================================================
package dao
import (
"hotgo/internal/dao/internal"
)
// internalSysDictDataDao is internal type for wrapping internal DAO implements.
type internalSysDictDataDao = *internal.SysDictDataDao
// sysDictDataDao is the data access object for table hg_sys_dict_data.
// You can define custom methods on it to extend its functionality as you wish.
type sysDictDataDao struct {
internalSysDictDataDao
}
var (
// SysDictData is globally common accessible object for table hg_sys_dict_data operations.
SysDictData = sysDictDataDao{
internal.NewSysDictDataDao(),
}
)
// Fill with you ideas below.

View File

@@ -0,0 +1,99 @@
// =================================================================================
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
// =================================================================================
package dao
import (
"context"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g"
"hotgo/internal/consts"
"hotgo/internal/dao/internal"
"hotgo/internal/model/entity"
)
// internalSysDictTypeDao is internal type for wrapping internal DAO implements.
type internalSysDictTypeDao = *internal.SysDictTypeDao
// sysDictTypeDao is the data access object for table hg_sys_dict_type.
// You can define custom methods on it to extend its functionality as you wish.
type sysDictTypeDao struct {
internalSysDictTypeDao
}
var (
// SysDictType is globally common accessible object for table hg_sys_dict_type operations.
SysDictType = sysDictTypeDao{
internal.NewSysDictTypeDao(),
}
)
// Fill with you ideas below.
// IsUniqueType 判断类型是否唯一
func (dao *sysDictTypeDao) IsUniqueType(ctx context.Context, id int64, typeName string) (bool, error) {
var data *entity.SysDictType
m := dao.Ctx(ctx).Where("type", typeName)
if id > 0 {
m = m.WhereNot("id", id)
}
if err := m.Scan(&data); err != nil {
err = gerror.Wrap(err, consts.ErrorORM)
return false, err
}
if data == nil {
return true, nil
}
return false, nil
}
// GetTypes 获取指定ID的所有类型标识包含下级
func (dao *sysDictTypeDao) GetTypes(ctx context.Context, id int64) (types []string, err error) {
m := dao.Ctx(ctx).Fields("type").Where("id", id).
WhereOr("pid", id).
Where("status", consts.StatusEnabled)
list, err := m.Array()
if err != nil {
err = gerror.Wrap(err, consts.ErrorORM)
return types, err
}
for _, v := range list {
types = append(types, v.String())
}
g.Log().Warningf(ctx, "types:%+v", types)
return types, nil
}
// GetType 获取指定ID的类型标识
func (dao *sysDictTypeDao) GetType(ctx context.Context, id int64) (types string, err error) {
m := dao.Ctx(ctx).Fields("type").Where("id", id).
Where("status", consts.StatusEnabled)
list, err := m.Value()
if err != nil {
err = gerror.Wrap(err, consts.ErrorORM)
return types, err
}
g.Log().Warningf(ctx, "GetType types:%+v", list.String())
return list.String(), nil
}
// GetId 获取指定类型的ID
func (dao *sysDictTypeDao) GetId(ctx context.Context, t string) (id int64, err error) {
m := dao.Ctx(ctx).Fields("id").Where("type", t).
Where("status", consts.StatusEnabled)
list, err := m.Value()
if err != nil {
err = gerror.Wrap(err, consts.ErrorORM)
return 0, err
}
return list.Int64(), nil
}

View File

@@ -0,0 +1,27 @@
// =================================================================================
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
// =================================================================================
package dao
import (
"hotgo/internal/dao/internal"
)
// internalSysLogDao is internal type for wrapping internal DAO implements.
type internalSysLogDao = *internal.SysLogDao
// sysLogDao is the data access object for table hg_sys_log.
// You can define custom methods on it to extend its functionality as you wish.
type sysLogDao struct {
internalSysLogDao
}
var (
// SysLog is globally common accessible object for table hg_sys_log operations.
SysLog = sysLogDao{
internal.NewSysLogDao(),
}
)
// Fill with you ideas below.

View File

@@ -0,0 +1,66 @@
// =================================================================================
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
// =================================================================================
package dao
import (
"context"
"github.com/gogf/gf/v2/container/gvar"
"github.com/gogf/gf/v2/errors/gerror"
"hotgo/internal/consts"
"hotgo/internal/dao/internal"
)
// internalSysProvincesDao is internal type for wrapping internal DAO implements.
type internalSysProvincesDao = *internal.SysProvincesDao
// sysProvincesDao is the data access object for table hg_sys_provinces.
// You can define custom methods on it to extend its functionality as you wish.
type sysProvincesDao struct {
internalSysProvincesDao
}
var (
// SysProvinces is globally common accessible object for table hg_sys_provinces operations.
SysProvinces = sysProvincesDao{
internal.NewSysProvincesDao(),
}
)
// Fill with you ideas below.
// GetRegion 获取省市编码对应的地区名称
func (dao *sysProvincesDao) GetRegion(ctx context.Context, province int, city int, spilt ...string) (string, error) {
var (
provinceName *gvar.Var
cityName *gvar.Var
err error
)
// TODO 默认分隔符
spiltSymbol := "-"
if len(spilt) > 0 {
spiltSymbol = spilt[0]
}
if province > 0 {
provinceName, err = dao.Ctx(ctx).Where("id", province).Fields("title").Value()
if err != nil {
err = gerror.Wrap(err, consts.ErrorORM)
return "", err
}
if city > 0 {
cityName, err = dao.Ctx(ctx).Where("id", city).Fields("title").Value()
if err != nil {
err = gerror.Wrap(err, consts.ErrorORM)
return "", err
}
}
} else {
return "内网IP", nil
}
return provinceName.String() + spiltSymbol + cityName.String(), nil
}

View File

@@ -0,0 +1,42 @@
// Package global
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package global
import (
"context"
"fmt"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/grpool"
"github.com/gogf/gf/v2/os/gtime"
"hotgo/internal/library/location"
"os"
)
func Init(ctx context.Context) {
// 默认上海时区
if err := gtime.SetTimeZone("Asia/Shanghai"); err != nil {
fmt.Printf("时区设置异常err%v \r\n", err)
return
}
RootPtah, _ = os.Getwd()
fmt.Printf("欢迎使用HotGo\r\n当前运行环境%v, 运行根路径为:%v \r\n", SysType, RootPtah)
loadMonitor(ctx)
}
func loadMonitor(ctx context.Context) {
err := grpool.AddWithRecover(ctx, func(ctx context.Context) {
MonitorData.STartTime = gtime.Now()
MonitorData.IntranetIP, _ = location.GetLocalIP()
MonitorData.PublicIP, _ = location.GetPublicIP()
})
if err != nil {
g.Log().Fatal(ctx, "global loadMonitor Fatal:", err)
return
}
}

View File

@@ -0,0 +1,21 @@
// Package global
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package global
import (
"hotgo/internal/model"
"runtime"
)
var (
// RootPtah 运行根路径
RootPtah string
// SysType 操作系统类型 windows | linux
SysType = runtime.GOOS
// MonitorData 监控数据
MonitorData model.MonitorData
)

24
server/internal/library/cache/cache.go vendored Normal file
View File

@@ -0,0 +1,24 @@
// Package cache
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package cache
import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gcache"
)
func New() *gcache.Cache {
c := gcache.New()
//redis
adapter := gcache.NewAdapterRedis(g.Redis())
//内存
//adapter := gcache.NewAdapterMemory()
c.SetAdapter(adapter)
return c
}

View File

@@ -0,0 +1,44 @@
// Package captcha
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package captcha
import (
"context"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/text/gstr"
"github.com/mojocn/base64Captcha"
)
// GetVerifyImgString 生成验证码
func GetVerifyImgString(ctx context.Context) (idKeyC string, base64stringC string) {
driver := &base64Captcha.DriverString{
Height: 80,
Width: 240,
//NoiseCount: 50,
//ShowLineOptions: 20,
Length: 4,
Source: "abcdefghjkmnpqrstuvwxyz23456789",
Fonts: []string{"chromohv.ttf"},
}
driver = driver.ConvertFonts()
store := base64Captcha.DefaultMemStore
c := base64Captcha.NewCaptcha(driver, store)
idKeyC, base64stringC, err := c.Generate()
if err != nil {
g.Log().Error(ctx, err)
}
return
}
// VerifyString 验证输入的验证码是否正确
func VerifyString(id, answer string) bool {
driver := new(base64Captcha.DriverString)
store := base64Captcha.DefaultMemStore
c := base64Captcha.NewCaptcha(driver, store)
answer = gstr.ToLower(answer)
return c.Verify(id, answer, true)
}

View File

@@ -0,0 +1,324 @@
// Package casbin
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package casbin
import (
"context"
"errors"
"fmt"
"github.com/casbin/casbin/v2/model"
"github.com/casbin/casbin/v2/persist"
"github.com/gogf/gf/v2/database/gdb"
"log"
"math"
"strings"
)
const (
defaultTableName = "hg_admin_role_casbin"
dropPolicyTableSql = `DROP TABLE IF EXISTS %s`
createPolicyTableSql = `
CREATE TABLE IF NOT EXISTS %s (
id bigint(20) NOT NULL AUTO_INCREMENT,
p_type varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
v0 varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
v1 varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
v2 varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
v3 varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
v4 varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
v5 varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (id) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = 'casbin权限表' ROW_FORMAT = Dynamic;
`
)
type (
adapter struct {
db gdb.DB
table string
}
policyColumns struct {
ID string // ID
PType string // PType
V0 string // V0
V1 string // V1
V2 string // V2
V3 string // V3
V4 string // V4
V5 string // V5
}
// policy rule entity
policyRule struct {
ID int64 `orm:"id" json:"id"`
PType string `orm:"p_type" json:"p_type"`
V0 string `orm:"v0" json:"v0"`
V1 string `orm:"v1" json:"v1"`
V2 string `orm:"v2" json:"v2"`
V3 string `orm:"v3" json:"v3"`
V4 string `orm:"v4" json:"v4"`
V5 string `orm:"v5" json:"v5"`
}
)
var (
errInvalidDatabaseLink = errors.New("invalid database link")
policyColumnsName = policyColumns{
ID: "id",
PType: "p_type",
V0: "v0",
V1: "v1",
V2: "v2",
V3: "v3",
V4: "v4",
V5: "v5",
}
)
// NewAdapter Create a casbin adapter
func NewAdapter(link string) (adp *adapter, err error) {
adp = &adapter{table: defaultTableName}
config := strings.SplitN(link, ":", 2)
if len(config) != 2 {
err = errInvalidDatabaseLink
return
}
if adp.db, err = gdb.New(gdb.ConfigNode{Type: config[0], Link: config[1]}); err != nil {
return
}
err = adp.createPolicyTable()
return
}
func (a *adapter) model() *gdb.Model {
return a.db.Model(a.table).Safe().Ctx(context.TODO())
}
// create a policy table when it's not exists.
func (a *adapter) createPolicyTable() (err error) {
_, err = a.db.Exec(context.TODO(), fmt.Sprintf(createPolicyTableSql, a.table))
return
}
// drop policy table from the storage.
func (a *adapter) dropPolicyTable() (err error) {
_, err = a.db.Exec(context.TODO(), fmt.Sprintf(dropPolicyTableSql, a.table))
return
}
// LoadPolicy loads all policy rules from the storage.
func (a *adapter) LoadPolicy(model model.Model) (err error) {
log.Println("LoadPolicy...")
var rules []policyRule
if err = a.model().Scan(&rules); err != nil {
return
}
for _, rule := range rules {
a.loadPolicyRule(rule, model)
}
return
}
// SavePolicy Saves all policy rules to the storage.
func (a *adapter) SavePolicy(model model.Model) (err error) {
if err = a.dropPolicyTable(); err != nil {
return
}
if err = a.createPolicyTable(); err != nil {
return
}
policyRules := make([]policyRule, 0)
for ptype, ast := range model["p"] {
for _, rule := range ast.Policy {
policyRules = append(policyRules, a.buildPolicyRule(ptype, rule))
}
}
for ptype, ast := range model["g"] {
for _, rule := range ast.Policy {
policyRules = append(policyRules, a.buildPolicyRule(ptype, rule))
}
}
if count := len(policyRules); count > 0 {
if _, err = a.model().Insert(policyRules); err != nil {
return
}
}
return
}
// AddPolicy adds a policy rule to the storage.
func (a *adapter) AddPolicy(sec string, ptype string, rule []string) (err error) {
_, err = a.model().Insert(a.buildPolicyRule(ptype, rule))
return
}
// AddPolicies adds policy rules to the storage.
func (a *adapter) AddPolicies(sec string, ptype string, rules [][]string) (err error) {
if len(rules) == 0 {
return
}
policyRules := make([]policyRule, 0, len(rules))
for _, rule := range rules {
policyRules = append(policyRules, a.buildPolicyRule(ptype, rule))
}
_, err = a.model().Insert(policyRules)
return
}
// RemovePolicy removes a policy rule from the storage.
func (a *adapter) RemovePolicy(sec string, ptype string, rule []string) (err error) {
db := a.model()
db = db.Where(policyColumnsName.PType, ptype)
for index := 0; index < len(rule); index++ {
db = db.Where(fmt.Sprintf("v%d", index), rule[index])
}
_, err = db.Delete()
return err
}
// RemoveFilteredPolicy removes policy rules that match the filter from the storage.
func (a *adapter) RemoveFilteredPolicy(sec string, ptype string, fieldIndex int, fieldValues ...string) (err error) {
db := a.model()
db = db.Where(policyColumnsName.PType, ptype)
for index := 0; index <= 5; index++ {
if fieldIndex <= index && index < fieldIndex+len(fieldValues) {
db = db.Where(fmt.Sprintf("v%d", index), fieldValues[index-fieldIndex])
}
}
_, err = db.Delete()
return
}
// RemovePolicies removes policy rules from the storage (implements the persist.BatchAdapter interface).
func (a *adapter) RemovePolicies(sec string, ptype string, rules [][]string) (err error) {
db := a.model()
for _, rule := range rules {
where := map[string]interface{}{policyColumnsName.PType: ptype}
for i := 0; i <= 5; i++ {
if len(rule) > i {
where[fmt.Sprintf("v%d", i)] = rule[i]
}
}
db = db.WhereOr(where)
}
_, err = db.Delete()
return
}
// UpdatePolicy updates a policy rule from storage.
func (a *adapter) UpdatePolicy(sec string, ptype string, oldRule, newRule []string) (err error) {
_, err = a.model().Update(a.buildPolicyRule(ptype, newRule), a.buildPolicyRule(ptype, oldRule))
return
}
// UpdatePolicies updates some policy rules to storage, like db, redis.
func (a *adapter) UpdatePolicies(sec string, ptype string, oldRules, newRules [][]string) (err error) {
if len(oldRules) == 0 || len(newRules) == 0 {
return
}
err = a.db.Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error {
for i := 0; i < int(math.Min(float64(len(oldRules)), float64(len(newRules)))); i++ {
if _, err = tx.Model(a.table).Update(a.buildPolicyRule(ptype, newRules[i]), a.buildPolicyRule(ptype, oldRules[i])); err != nil {
return err
}
}
return nil
})
return
}
// 加载策略规则
func (a *adapter) loadPolicyRule(rule policyRule, model model.Model) {
ruleText := rule.PType
if rule.V0 != "" {
ruleText += ", " + rule.V0
}
if rule.V1 != "" {
ruleText += ", " + rule.V1
}
if rule.V2 != "" {
ruleText += ", " + rule.V2
}
if rule.V3 != "" {
ruleText += ", " + rule.V3
}
if rule.V4 != "" {
ruleText += ", " + rule.V4
}
if rule.V5 != "" {
ruleText += ", " + rule.V5
}
persist.LoadPolicyLine(ruleText, model)
}
// 构建策略规则
func (a *adapter) buildPolicyRule(ptype string, data []string) policyRule {
rule := policyRule{PType: ptype}
if len(data) > 0 {
rule.V0 = data[0]
}
if len(data) > 1 {
rule.V1 = data[1]
}
if len(data) > 2 {
rule.V2 = data[2]
}
if len(data) > 3 {
rule.V3 = data[3]
}
if len(data) > 4 {
rule.V4 = data[4]
}
if len(data) > 5 {
rule.V5 = data[5]
}
return rule
}

View File

@@ -0,0 +1,68 @@
// Package casbin
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package casbin
import (
"context"
"net/http"
"testing"
)
// TestNew description
func TestNew(t *testing.T) {
InitEnforcer(context.TODO())
user := "admin"
path := "/"
method := http.MethodGet
t.Logf("\nuser:%v\npath:%v\nmethod:%v", user, path, method)
ok, err := Enforcer.DeletePermissionsForUser(user)
if err != nil {
t.Error(err)
}
t.Logf("delete user premission:%v", ok)
CheckPremission(t, user, path, method)
AddPremission(t, user, "*", ActionAll)
CheckPremission(t, user, path, method)
user1 := "user1"
path1 := "/api/v1/*"
checkPathTrue := "/api/v1/user/list"
checkPathFalse := "/api/v2/user/list"
AddPremission(t, user1, path1, ActionAll)
CheckPremission(t, user1, checkPathTrue, ActionPost)
CheckPremission(t, user1, checkPathFalse, http.MethodGet)
CheckPremission(t, user1, checkPathTrue, http.MethodGet)
CheckPremission(t, user1, "/api/v1/user/list2", http.MethodGet)
ok, err = Enforcer.DeletePermissionsForUser(user1)
if err != nil {
t.Error(err)
}
t.Logf("delete user premission:%v", ok)
CheckPremission(t, user1, "/api/v1/user1/list", http.MethodGet)
}
// CheckPremission description
func CheckPremission(t *testing.T, user string, path string, method string) {
ok, err := Enforcer.Enforce(user, path, method)
if err != nil {
t.Error(err)
}
t.Logf("check \tuser[%s] \tpremission[%s] \tpath[%s] \tallow[%v]", user, method, path, ok)
}
// Add description
func AddPremission(t *testing.T, user string, path string, method string) {
ok, err := Enforcer.AddPolicy(user, path, method)
if err != nil {
t.Error(err)
}
t.Logf("add \tuser[%s] \tpremission[%s] \tpath[%s] \tresult[%v]", user, method, path, ok)
}

View File

@@ -0,0 +1,113 @@
// Package casbin
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package casbin
import (
"context"
"github.com/casbin/casbin/v2"
_ "github.com/gogf/gf/contrib/drivers/mysql/v2"
"github.com/gogf/gf/v2/frame/g"
"hotgo/internal/consts"
"net/http"
"strings"
)
const (
ActionGet = http.MethodGet
ActionPost = http.MethodPost
ActionPut = http.MethodPut
ActionDelete = http.MethodDelete
ActionAll = "GET|POST|PUT|DELETE|PATCH|OPTIONS|HEAD"
)
var Enforcer *casbin.Enforcer
// InitEnforcer 初始化
func InitEnforcer(ctx context.Context) {
var (
link, _ = g.Cfg().Get(ctx, "database.default.link")
a, err = NewAdapter(link.String())
)
if err != nil {
g.Log().Panicf(ctx, "casbin.NewAdapter err . %v", err)
return
}
Enforcer, err = casbin.NewEnforcer("./manifest/config/casbin.conf", a)
if err != nil {
g.Log().Panicf(ctx, "casbin.NewEnforcer err . %v", err)
return
}
loadPermissions(ctx)
}
func loadPermissions(ctx context.Context) {
type Policy struct {
Key string `json:"key"`
Permissions string `json:"permissions"`
}
var (
rules [][]string
polices []*Policy
err error
superRoleKey, _ = g.Cfg().Get(ctx, "hotgo.admin.superRoleKey")
)
err = g.Model("hg_admin_role r").
LeftJoin("hg_admin_role_menu rm", "r.id=rm.role_id").
LeftJoin("hg_admin_menu m", "rm.menu_id=m.id").
Fields("r.key,m.permissions").
Where("r.status", consts.StatusEnabled).
Where("m.status", consts.StatusEnabled).
Where("m.permissions !=?", "").
Where("r.key !=?", superRoleKey.String()).
Scan(&polices)
if err != nil {
g.Log().Fatalf(ctx, "loadPermissions Scan err:%v", err)
return
}
for _, policy := range polices {
if strings.Contains(policy.Permissions, ",") {
lst := strings.Split(policy.Permissions, ",")
for _, permissions := range lst {
rules = append(rules, []string{policy.Key, permissions, ActionAll})
}
} else {
rules = append(rules, []string{policy.Key, policy.Permissions, ActionAll})
}
}
if _, err = Enforcer.AddPolicies(rules); err != nil {
g.Log().Fatalf(ctx, "loadPermissions AddPolicies err:%v", err)
return
}
}
func Clear(ctx context.Context) (err error) {
_, err = Enforcer.RemovePolicies(Enforcer.GetPolicy())
if err != nil {
g.Log().Warningf(ctx, "Enforcer RemovePolicies err:%+v", err)
return
}
// 检查是否清理干净
if len(Enforcer.GetPolicy()) > 0 {
return Clear(ctx)
}
return
}
func Refresh(ctx context.Context) (err error) {
if err = Clear(ctx); err != nil {
return err
}
loadPermissions(ctx)
return
}

View File

@@ -0,0 +1,81 @@
// Package contexts
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package contexts
import (
"context"
"github.com/gogf/gf/v2/net/ghttp"
"hotgo/internal/consts"
"hotgo/internal/model"
)
// Init 初始化上下文对象指针到上下文对象中,以便后续的请求流程中可以修改
func Init(r *ghttp.Request, customCtx *model.Context) {
r.SetCtxVar(consts.ContextKey, customCtx)
}
// Get 获得上下文变量如果没有设置那么返回nil
func Get(ctx context.Context) *model.Context {
value := ctx.Value(consts.ContextKey)
if value == nil {
return nil
}
if localCtx, ok := value.(*model.Context); ok {
return localCtx
}
return nil
}
// SetUser 将上下文信息设置到上下文请求中,注意是完整覆盖
func SetUser(ctx context.Context, user *model.Identity) {
Get(ctx).User = user
}
// SetResponse 设置组件响应 用于全局日志使用
func SetResponse(ctx context.Context, response *model.Response) {
Get(ctx).Response = response
}
// SetModule 设置应用模块
func SetModule(ctx context.Context, module string) {
Get(ctx).Module = module
}
// SetTakeUpTime 设置请求耗时
func SetTakeUpTime(ctx context.Context, takeUpTime int64) {
Get(ctx).TakeUpTime = takeUpTime
}
// GetUserId 获取用户ID
func GetUserId(ctx context.Context) int64 {
user := Get(ctx).User
if user == nil {
return 0
}
return user.Id
}
// GetRoleId 获取用户角色ID
func GetRoleId(ctx context.Context) int64 {
user := Get(ctx).User
if user == nil {
return 0
}
return user.Role
}
// GetRoleKey 获取用户角色唯一编码
func GetRoleKey(ctx context.Context) string {
user := Get(ctx).User
if user == nil {
return ""
}
return user.RoleKey
}

View File

@@ -0,0 +1,70 @@
// Package ems
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package ems
import (
"github.com/gogf/gf/v2/errors/gerror"
"hotgo/internal/model"
"hotgo/utility/validate"
"net/smtp"
"strings"
)
// Send 发送邮件入口
func Send(config *model.EmailConfig, to string, subject string, body string) error {
return sendToMail(config, to, subject, body, "html")
}
// SendTestMail 发送测试邮件
func SendTestMail(config *model.EmailConfig, to string) error {
subject := "这是一封来自HotGo的测试邮件"
body := `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="iso-8859-15">
<title>这是一封来自HotGo的测试邮件</title>
</head>
<body>
当你收到这封邮件的时候,说明已经联调成功了,恭喜你!
</body>
</html>`
return Send(config, to, subject, body)
}
func sendToMail(config *model.EmailConfig, to, subject, body, mailType string) error {
if config == nil {
return gerror.New("邮件配置不能为空")
}
var (
contentType string
auth = smtp.PlainAuth("", config.User, config.Password, config.Host)
sendTo = strings.Split(to, ";")
)
if len(sendTo) == 0 {
return gerror.New("收件人不能为空")
}
for _, em := range sendTo {
if !validate.IsEmail(em) {
return gerror.Newf("邮件格式不正确,请检查:%v", em)
}
}
if mailType == "html" {
contentType = "Content-Type: text/" + mailType + "; charset=UTF-8"
} else {
contentType = "Content-Type: text/plain" + "; charset=UTF-8"
}
msg := []byte("To: " + to + "\r\nFrom: " + config.SendName + "<" + config.User + ">" + "\r\nSubject: " + subject + "\r\n" + contentType + "\r\n\r\n" + body)
return smtp.SendMail(config.Addr, auth, config.User, sendTo, msg)
}

View File

@@ -0,0 +1,112 @@
// Package jwt
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package jwt
import (
"context"
"fmt"
j "github.com/dgrijalva/jwt-go"
"github.com/gogf/gf/v2/crypto/gmd5"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
"github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/v2/util/gconv"
"hotgo/internal/consts"
"hotgo/internal/library/cache"
"hotgo/internal/model"
"time"
)
// GenerateLoginToken 为指定用户生成token
func GenerateLoginToken(ctx context.Context, user *model.Identity, isRefresh bool) (interface{}, error) {
var (
jwtVersion, _ = g.Cfg().Get(ctx, "jwt.version", "1.0")
jwtSign, _ = g.Cfg().Get(ctx, "jwt.sign", "hotGo")
token = j.NewWithClaims(j.SigningMethodHS256, j.MapClaims{
"id": user.Id,
"username": user.Username,
"realname": user.RealName,
"avatar": user.Avatar,
"email": user.Email,
"mobile": user.Mobile,
"last_time": user.LastTime,
"last_ip": user.LastIp,
"exp": user.Exp,
"expires": user.Expires,
"app": user.App,
"role": user.Role,
"role_key": user.RoleKey,
"visit_count": user.VisitCount,
"is_refresh": isRefresh,
"jwt_version": jwtVersion.String(),
})
)
tokenString, err := token.SignedString(jwtSign.Bytes())
if err != nil {
return nil, gerror.New(err.Error())
}
var (
tokenStringMd5 = gmd5.MustEncryptString(tokenString)
// 绑定登录token
c = cache.New()
key = consts.RedisJwtToken + tokenStringMd5
// 将有效期转为持续时间,单位:秒
expires, _ = time.ParseDuration(fmt.Sprintf("+%vs", user.Expires))
)
err = c.Set(ctx, key, tokenString, expires)
if err != nil {
return nil, gerror.New(err.Error())
}
err = c.Set(ctx, consts.RedisJwtUserBind+user.App+":"+gconv.String(user.Id), key, expires)
if err != nil {
return nil, gerror.New(err.Error())
}
return tokenString, err
}
// ParseToken 解析token
func ParseToken(tokenString string, secret []byte) (j.MapClaims, error) {
if tokenString == "" {
err := gerror.New("token 为空")
return nil, err
}
token, err := j.Parse(tokenString, func(token *j.Token) (interface{}, error) {
if _, ok := token.Method.(*j.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return secret, nil
})
if token == nil {
err := gerror.New("token不存在")
return nil, err
}
if claims, ok := token.Claims.(j.MapClaims); ok && token.Valid {
return claims, nil
} else {
return nil, err
}
}
// GetAuthorization 获取authorization
func GetAuthorization(r *ghttp.Request) string {
// 默认从请求头获取
var authorization = r.Header.Get("Authorization")
// 如果请求头不存在则从get参数获取
if authorization == "" {
return r.Get("authorization").String()
}
return gstr.Replace(authorization, "Bearer ", "")
}

View File

@@ -0,0 +1,197 @@
// Package location
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package location
import (
"context"
"github.com/axgle/mahonia"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
"github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/v2/util/gconv"
"github.com/kayon/iploc"
"hotgo/utility/validate"
"io/ioutil"
"net"
"net/http"
"strings"
"time"
)
type IpLocationData struct {
Ip string `json:"ip"`
Country string `json:"country"`
Region string `json:"region"`
Province string `json:"province"`
ProvinceCode int64 `json:"province_code"`
City string `json:"city"`
CityCode int64 `json:"city_code"`
Area string `json:"area"`
AreaCode int64 `json:"area_code"`
}
// WhoisLocation 通过Whois接口查询IP归属地
func WhoisLocation(ctx context.Context, ip string) IpLocationData {
type whoisRegionData struct {
Ip string `json:"ip"`
Pro string `json:"pro" `
ProCode string `json:"proCode" `
City string `json:"city" `
CityCode string `json:"cityCode"`
Region string `json:"region"`
RegionCode string `json:"regionCode"`
Addr string `json:"addr"`
Err string `json:"err"`
}
if !validate.IsIp(ip) {
return IpLocationData{}
}
response, err := g.Client().Timeout(10*time.Second).Get(ctx, "http://whois.pconline.com.cn/ipJson.jsp?ip="+ip+"&json=true")
if err != nil {
err = gerror.New(err.Error())
return IpLocationData{
Ip: ip,
}
}
defer response.Close()
var enc mahonia.Decoder
enc = mahonia.NewDecoder("gbk")
data := enc.ConvertString(response.ReadAllString())
whoisData := whoisRegionData{}
if err := gconv.Struct(data, &whoisData); err != nil {
err = gerror.New(err.Error())
g.Log().Print(ctx, "err:", err)
return IpLocationData{
Ip: ip,
}
}
return IpLocationData{
Ip: whoisData.Ip,
//Country string `json:"country"`
Region: whoisData.Addr,
Province: whoisData.Pro,
ProvinceCode: gconv.Int64(whoisData.ProCode),
City: whoisData.City,
CityCode: gconv.Int64(whoisData.CityCode),
Area: whoisData.Region,
AreaCode: gconv.Int64(whoisData.RegionCode),
}
}
// Cz88Find 通过Cz88的IP库查询IP归属地
func Cz88Find(ctx context.Context, ip string) IpLocationData {
if !validate.IsIp(ip) {
g.Log().Print(ctx, "ip格式错误:", ip)
return IpLocationData{}
}
loc, err := iploc.OpenWithoutIndexes("./storage/ip/qqwry-utf8.dat")
if err != nil {
err = gerror.New(err.Error())
return IpLocationData{
Ip: ip,
}
}
detail := loc.Find(ip)
if detail == nil {
return IpLocationData{
Ip: ip,
}
}
locationData := IpLocationData{
Ip: ip,
Country: detail.Country,
Region: detail.Region,
Province: detail.Province,
City: detail.City,
Area: detail.County,
}
if gstr.LenRune(locationData.Province) == 0 {
return locationData
}
return locationData
}
// IsJurisByIpTitle 判断地区名称是否为直辖市
func IsJurisByIpTitle(title string) bool {
lists := []string{"北京市", "天津市", "重庆市", "上海市"}
for i := 0; i < len(lists); i++ {
if gstr.Contains(lists[i], title) {
return true
}
}
return false
}
// GetLocation 获取IP归属地信息
func GetLocation(ctx context.Context, ip string) IpLocationData {
method, _ := g.Cfg().Get(ctx, "hotgo.ipMethod", "cz88")
if method.String() == "whois" {
return WhoisLocation(ctx, ip)
}
return Cz88Find(ctx, ip)
}
// GetPublicIP 获取公网IP
func GetPublicIP() (ip string, err error) {
response, err := http.Get("http://members.3322.org/dyndns/getip")
if err != nil {
return
}
defer response.Body.Close()
body, _ := ioutil.ReadAll(response.Body)
ip = string(body)
ip = strings.ReplaceAll(ip, "\n", "")
return
}
// GetLocalIP 获取服务器内网IP
func GetLocalIP() (ip string, err error) {
addrs, err := net.InterfaceAddrs()
if err != nil {
return
}
for _, addr := range addrs {
ipAddr, ok := addr.(*net.IPNet)
if !ok {
continue
}
if ipAddr.IP.IsLoopback() {
continue
}
if !ipAddr.IP.IsGlobalUnicast() {
continue
}
return ipAddr.IP.String(), nil
}
return
}
// GetClientIp 获取客户端IP
func GetClientIp(r *ghttp.Request) string {
ip := r.Header.Get("X-Forwarded-For")
if ip == "" {
ip = r.GetClientIp()
}
return ip
}

View File

@@ -0,0 +1,83 @@
package feishu
import (
"encoding/json"
"fmt"
"strconv"
"time"
"github.com/go-resty/resty/v2"
"hotgo/internal/library/notify/feishu/internal/security"
)
const feishuAPI = "https://open.feishu.cn/open-apis/bot/v2/hook/"
// Client feishu client
type Client struct {
AccessToken string
Secret string
}
// NewClient new client
func NewClient(accessToken, secret string) *Client {
return &Client{
AccessToken: accessToken,
Secret: secret,
}
}
// Response response struct
type Response struct {
Code int64 `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data"`
Extra interface{} `json:"Extra"`
StatusCode int64 `json:"StatusCode"`
StatusMessage string `json:"StatusMessage"`
}
// Send send message
func (d *Client) Send(message Message) (string, *Response, error) {
res := &Response{}
if len(d.AccessToken) < 1 {
return "", res, fmt.Errorf("accessToken is empty")
}
timestamp := time.Now().Unix()
sign, err := security.GenSign(d.Secret, timestamp)
if err != nil {
return "", res, err
}
body := message.Body()
body["timestamp"] = strconv.FormatInt(timestamp, 10)
body["sign"] = sign
reqBytes, err := json.Marshal(body)
if err != nil {
return "", res, err
}
reqString := string(reqBytes)
client := resty.New()
URL := fmt.Sprintf("%v%v", feishuAPI, d.AccessToken)
resp, err := client.SetRetryCount(3).R().
SetBody(body).
SetHeader("Accept", "application/json").
SetHeader("Content-Type", "application/json").
SetResult(&Response{}).
ForceContentType("application/json").
Post(URL)
if err != nil {
return reqString, nil, err
}
result := resp.Result().(*Response)
if result.Code != 0 {
return reqString, result, fmt.Errorf("send message to feishu error = %s", result.Msg)
}
return reqString, result, nil
}

Some files were not shown because too many files have changed in this diff Show More