golangci-lint run

This commit is contained in:
孟帅
2023-07-24 09:35:30 +08:00
parent 071b6224c9
commit 996ed818ee
61 changed files with 527 additions and 271 deletions

View File

@@ -47,7 +47,7 @@ const { hasPermission } = usePermission();
type MenuRouteMeta struct {
// 解释参考https://naive-ui-admin-docs.vercel.app/guide/router.html#%E5%A4%9A%E7%BA%A7%E8%B7%AF%E7%94%B1
Title string `json:"title"` // 菜单名称 一般必填
//Disabled bool `json:"disabled,omitempty"` // 禁用菜单
// Disabled bool `json:"disabled,omitempty"` // 禁用菜单
Icon string `json:"icon,omitempty"` // 菜单图标
KeepAlive bool `json:"keepAlive,omitempty"` // 缓存该路由
Hidden bool `json:"hidden,omitempty"` // 隐藏菜单

View File

@@ -31,7 +31,7 @@
### 生成模板配置
- 注意线上环境务必将allowedIPs参数设为空考虑到项目安全问题请勿线上生成使用
- 注意:线上环境务必将`allowedIPs`参数设为空,考虑到项目安全问题请勿线上生成使用!
- 默认配置路径server/manifest/config/config.yaml

View File

@@ -114,7 +114,8 @@ func (c *cHello) Hello(ctx context.Context, req *user.HelloReq) (res *user.Hello
```
- 浏览器中访问响应内容如下:
![./images/sys-middleware-com-response.png](./images/sys-middleware-com-response.png)
![./images/sys-middleware-com-response.png](./images/sys-middleware-com-response.png)
#### 自定义响应

View File

@@ -3,6 +3,7 @@
目录
- 配置文件
- 实现接口
- 一个例子
- 控制台
- 自定义队列驱动
@@ -42,6 +43,18 @@ queue:
```
### 实现接口
- 为了提供高度的扩展性,消费队列在设计上采用了接口化的思路。只需要实现以下接口,您就可以在任何地方注册和使用消费队列消费功能,从而实现更大的灵活性和可扩展性。
```go
// Consumer 消费者接口,实现该接口即可加入到消费队列中
type Consumer interface {
GetTopic() string // 获取消费主题
Handle(ctx context.Context, mqMsg MqMsg) (err error) // 处理消息的方法
}
```
### 一个例子
每个被发送到队列的消息应该被定义为一个单独的文件结构。

View File

@@ -1,3 +1,283 @@
## This file contains all available configuration options
## with their default values.
# See https://github.com/golangci/golangci-lint#config-file
# See https://golangci-lint.run/usage/configuration/
# Options for analysis running.
run:
skip-dirs: # 设置要忽略的目录
# Exit code when at least one issue was found.
# Default: 1
issues-exit-code: 2
# Include test files or not.
# Default: true
tests: false
# Which dirs to skip: issues from them won't be reported.
# Can use regexp here: `generated.*`, regexp is applied on full path.
# Default value is empty list,
# but default dirs are skipped independently of this option's value (see skip-dirs-use-default).
# "/" will be replaced by current OS file path separator to properly work on Windows.
skip-dirs:
- internal/library/hggen/internal
# Which files to skip: they will be analyzed, but issues from them won't be reported.
# Default value is empty list,
# but there is no need to include all autogenerated files,
# we confidently recognize autogenerated files.
# If it's not please let us know.
# "/" will be replaced by current OS file path separator to properly work on Windows.
skip-files: []
# Main linters configurations.
# See https://golangci-lint.run/usage/linters
linters:
# Disable all default enabled linters.
disable-all: true
# Custom enable linters we want to use.
enable:
- errcheck # Errcheck is a program for checking for unchecked errors in go programs.
- errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occasions, where the check for the returned error can be omitted.
- funlen # Tool for detection of long functions
- goconst # Finds repeated strings that could be replaced by a constant
- gocritic # Provides diagnostics that check for bugs, performance and style issues.
# - gofmt # Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification
- gosimple # Linter for Go source code that specializes in simplifying code
- govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string
- misspell # Finds commonly misspelled English words in comments
- nolintlint # Reports ill-formed or insufficient nolint directives
- revive # Fast, configurable, extensible, flexible, and beautiful linter for Go. Drop-in replacement of golint.
- staticcheck # It's a set of rules from staticcheck. It's not the same thing as the staticcheck binary.
- typecheck # Like the front-end of a Go compiler, parses and type-checks Go code
- usestdlibvars # A linter that detect the possibility to use variables/constants from the Go standard library.
- whitespace # Tool for detection of leading and trailing whitespace
issues:
exclude-rules:
# helpers in tests often (rightfully) pass a *testing.T as their first argument
- path: _test\.go
text: "context.Context should be the first parameter of a function"
linters:
- revive
# Yes, they are, but it's okay in a test
- path: _test\.go
text: "exported func.*returns unexported type.*which can be annoying to use"
linters:
- revive
# https://github.com/go-critic/go-critic/issues/926
- linters:
- gocritic
text: "unnecessaryDefer:"
# https://golangci-lint.run/usage/linters
linters-settings:
# https://golangci-lint.run/usage/linters/#misspell
misspell:
locale: US
ignore-words:
- cancelled
# https://golangci-lint.run/usage/linters/#revive
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md
revive:
ignore-generated-header: true
severity: error
rules:
- name: atomic
- name: line-length-limit
severity: error
arguments: [ 1024 ]
- name: unhandled-error
severity: warning
disabled: true
arguments: []
- name: var-naming
severity: warning
disabled: true
arguments:
# AllowList
- [ "ID","URL","IP","HTTP","JSON","API","UID","Id","Api","Uid","Http","Json","Ip","Url" ]
# DenyList
- [ "VM" ]
- name: string-format
severity: warning
disabled: false
arguments:
- - 'core.WriteError[1].Message'
- '/^([^A-Z]|$)/'
- must not start with a capital letter
- - 'fmt.Errorf[0]'
- '/(^|[^\.!?])$/'
- must not end in punctuation
- - panic
- '/^[^\n]*$/'
- must not contain line breaks
- name: function-result-limit
severity: warning
disabled: false
arguments: [ 4 ]
# https://golangci-lint.run/usage/linters/#funlen
funlen:
# Checks the number of lines in a function.
# If lower than 0, disable the check.
# Default: 60
lines: 330
# Checks the number of statements in a function.
# If lower than 0, disable the check.
# Default: 40
statements: -1
# https://golangci-lint.run/usage/linters/#goconst
goconst:
# Minimal length of string constant.
# Default: 3
min-len: 4
# Minimum occurrences of constant string count to trigger issue.
# Default: 3
# For subsequent optimization, the value is reduced.
min-occurrences: 30
# Ignore test files.
# Default: false
ignore-tests: true
# Look for existing constants matching the values.
# Default: true
match-constant: false
# Search also for duplicated numbers.
# Default: false
numbers: true
# Minimum value, only works with goconst.numbers
# Default: 3
min: 5
# Maximum value, only works with goconst.numbers
# Default: 3
max: 20
# Ignore when constant is not used as function argument.
# Default: true
ignore-calls: false
# https://golangci-lint.run/usage/linters/#gocritic
gocritic:
disabled-checks:
- ifElseChain
- assignOp
- appendAssign
- singleCaseSwitch
- regexpMust
- typeSwitchVar
- elseif
# https://golangci-lint.run/usage/linters/#gosimple
gosimple:
# Select the Go version to target.
# Default: 1.13
# Deprecated: use the global `run.go` instead.
go: "1.15"
# Sxxxx checks in https://staticcheck.io/docs/configuration/options/#checks
# Default: ["*"]
checks: [
"all", "-S1000", "-S1001", "-S1002", "-S1008", "-S1009", "-S1016", "-S1023", "-S1025", "-S1029", "-S1034", "-S1040"
]
# https://golangci-lint.run/usage/linters/#govet
govet:
# Report about shadowed variables.
# Default: false
check-shadowing: true
# Settings per analyzer.
settings:
# Analyzer name, run `go tool vet help` to see all analyzers.
printf:
# Comma-separated list of print function names to check (in addition to default, see `go tool vet help printf`).
# Default: []
funcs:
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Infof
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Warnf
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Errorf
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Fatalf
# shadow:
# Whether to be strict about shadowing; can be noisy.
# Default: false
# strict: false
unusedresult:
# Comma-separated list of functions whose results must be used
# (in addition to defaults context.WithCancel,context.WithDeadline,context.WithTimeout,context.WithValue,
# errors.New,fmt.Errorf,fmt.Sprint,fmt.Sprintf,sort.Reverse)
# Default []
funcs:
- pkg.MyFunc
- context.WithCancel
# Comma-separated list of names of methods of type func() string whose results must be used
# (in addition to default Error,String)
# Default []
stringmethods:
- MyMethod
# Enable all analyzers.
# Default: false
enable-all: true
# Disable analyzers by name.
# Run `go tool vet help` to see all analyzers.
# Default: []
disable:
- asmdecl
- assign
- atomic
- atomicalign
- bools
- buildtag
- cgocall
- composites
- copylocks
- deepequalerrors
- errorsas
- fieldalignment
- findcall
- framepointer
- httpresponse
- ifaceassert
- loopclosure
- lostcancel
- nilfunc
- nilness
- reflectvaluecompare
- shift
- shadow
- sigchanyzer
- sortslice
- stdmethods
- stringintconv
- structtag
- testinggoroutine
- tests
- unmarshal
- unreachable
- unsafeptr
- unusedwrite
# https://golangci-lint.run/usage/linters/#staticcheck
staticcheck:
# Select the Go version to target.
# Default: "1.13"
# Deprecated: use the global `run.go` instead.
go: "1.15"
# SAxxxx checks in https://staticcheck.io/docs/configuration/options/#checks
# Default: ["*"]
checks: [ "all","-SA1019","-SA4015","-SA1029","-SA1016","-SA9003","-SA4006","-SA6003" ]
# https://golangci-lint.run/usage/linters/#gofmt
gofmt:
# Simplify code: gofmt with `-s` option.
# Default: true
simplify: true
# Apply the rewrite rules to the source before reformatting.
# https://pkg.go.dev/cmd/gofmt
# Default: []
rewrite-rules: [ ]
# - pattern: 'interface{}'
# replacement: 'any'
# - pattern: 'a[b:len(a)]'
# replacement: 'a[b:]'

View File

@@ -87,14 +87,6 @@ func (s *sSysTable) List(ctx context.Context, in *sysin.TableListInp) (list []*s
mod = mod.Where(fmt.Sprintf(`JSON_CONTAINS(%s,'%v')`, cols.Hobby, in.Hobby))
}
//// 关联表testCategory
//mod = mod.LeftJoin(hgorm.GenJoinOnRelation(
// dao.AddonHgexampleTable.Table(), cols.CategoryId, // 主表表名,关联条件
// dao.AddonHgexampleTableCategory.Table(), "testCategory", dao.AddonHgexampleTableCategory.Columns().Id, // 关联表表名,别名,关联条件
//)...)
//
//mod = mod.Where(`testCategory.`+dao.AddonHgexampleTableCategory.Columns().Name, "微信公众号")
totalCount, err = mod.Clone().Count(1)
if err != nil {
err = gerror.Wrap(err, "获取表格数据行失败,请稍后重试!")

View File

@@ -36,5 +36,4 @@ func WebSocket(ctx context.Context, group *ghttp.RouterGroup) {
ws.RegisterMsg(ws.EventHandlers{
// ...
})
}

View File

@@ -67,7 +67,6 @@ type SiteConfigRes struct {
Version string `json:"version" dc:"系统版本"`
WsAddr string `json:"wsAddr" dc:"客户端websocket地址"`
Domain string `json:"domain" dc:"对外域名"`
//InviteUrl string `json:"inviteUrl" dc:"邀请注册地址"`
}
// SiteLoginConfigReq 获取登录配置

View File

@@ -52,7 +52,7 @@ type MaxSortReq struct {
}
type MaxSortRes struct {
Sort int `json:"sort" dc:"排序"`
*adminin.DeptMaxSortModel
}
// StatusReq 更新部门状态

View File

@@ -12,7 +12,6 @@ type CronDeleteReq struct {
type CronDeleteRes struct {
tcp.ServerRes
sysin.CronDeleteModel
}
// CronEditReq 编辑任务
@@ -22,7 +21,6 @@ type CronEditReq struct {
type CronEditRes struct {
tcp.ServerRes
*sysin.CronEditModel
}
// CronStatusReq 修改任务状态
@@ -32,7 +30,6 @@ type CronStatusReq struct {
type CronStatusRes struct {
tcp.ServerRes
*sysin.CronStatusModel
}
// CronOnlineExecReq 在线执行
@@ -42,5 +39,4 @@ type CronOnlineExecReq struct {
type CronOnlineExecRes struct {
tcp.ServerRes
*sysin.OnlineExecModel
}

View File

@@ -555,7 +555,6 @@ golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMk
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
golang.org/x/image v0.0.0-20190501045829-6d32002ffd75/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.0.0-20211028202545-6944b10bf410 h1:hTftEOvwiOq2+O8k2D5/Q7COC7k5Qcrgc2TFURJYnvQ=
golang.org/x/image v0.0.0-20211028202545-6944b10bf410/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM=
golang.org/x/image v0.1.0 h1:r8Oj8ZA2Xy12/b5KZYj3tuv7NG/fBz3TwQVvpJ9l8Rk=
golang.org/x/image v0.1.0/go.mod h1:iyPr49SD/G/TBxYVB/9RRtGUT5eNbo2u4NamWeQcD5c=

View File

@@ -31,13 +31,8 @@ func (c *cDept) Edit(ctx context.Context, req *dept.EditReq) (res *dept.EditRes,
// MaxSort 最大排序
func (c *cDept) MaxSort(ctx context.Context, req *dept.MaxSortReq) (res *dept.MaxSortRes, err error) {
data, err := service.AdminDept().MaxSort(ctx, &req.DeptMaxSortInp)
if err != nil {
return
}
res = new(dept.MaxSortRes)
res.Sort = data.Sort
res.DeptMaxSortModel, err = service.AdminDept().MaxSort(ctx, &req.DeptMaxSortInp)
return
}

View File

@@ -32,13 +32,8 @@ func (c *cNotice) Edit(ctx context.Context, req *notice.EditReq) (res *notice.Ed
// MaxSort 最大排序
func (c *cNotice) MaxSort(ctx context.Context, req *notice.MaxSortReq) (res *notice.MaxSortRes, err error) {
data, err := service.AdminNotice().MaxSort(ctx, &req.NoticeMaxSortInp)
if err != nil {
return
}
res = new(notice.MaxSortRes)
res.Sort = data.Sort
res.NoticeMaxSortModel, err = service.AdminNotice().MaxSort(ctx, &req.NoticeMaxSortInp)
return
}

View File

@@ -30,13 +30,8 @@ func (c *cPost) Edit(ctx context.Context, req *post.EditReq) (res *post.EditRes,
// MaxSort 最大排序
func (c *cPost) MaxSort(ctx context.Context, req *post.MaxSortReq) (res *post.MaxSortRes, err error) {
data, err := service.AdminPost().MaxSort(ctx, &req.PostMaxSortInp)
if err != nil {
return
}
res = new(post.MaxSortRes)
res.Sort = data.Sort
res.PostMaxSortModel, err = service.AdminPost().MaxSort(ctx, &req.PostMaxSortInp)
return
}

View File

@@ -33,13 +33,8 @@ func (c *cCron) Edit(ctx context.Context, req *cron.EditReq) (res *cron.EditRes,
// MaxSort 最大排序
func (c *cCron) MaxSort(ctx context.Context, req *cron.MaxSortReq) (res *cron.MaxSortRes, err error) {
data, err := service.SysCron().MaxSort(ctx, &req.CronMaxSortInp)
if err != nil {
return
}
res = new(cron.MaxSortRes)
res.Sort = data.Sort
res.CronMaxSortModel, err = service.SysCron().MaxSort(ctx, &req.CronMaxSortInp)
return
}

View File

@@ -31,13 +31,8 @@ func (c *cCronGroup) Edit(ctx context.Context, req *cron.GroupEditReq) (res *cro
// MaxSort 最大排序
func (c *cCronGroup) MaxSort(ctx context.Context, req *cron.GroupMaxSortReq) (res *cron.GroupMaxSortRes, err error) {
data, err := service.SysCronGroup().MaxSort(ctx, &req.CronGroupMaxSortInp)
if err != nil {
return
}
res = new(cron.GroupMaxSortRes)
res.Sort = data.Sort
res.CronGroupMaxSortModel, err = service.SysCronGroup().MaxSort(ctx, &req.CronGroupMaxSortInp)
return
}

View File

@@ -37,13 +37,8 @@ func (c *cGenCodes) Edit(ctx context.Context, req *gencodes.EditReq) (res *genco
// MaxSort 最大排序
func (c *cGenCodes) MaxSort(ctx context.Context, req *gencodes.MaxSortReq) (res *gencodes.MaxSortRes, err error) {
data, err := service.SysGenCodes().MaxSort(ctx, &req.GenCodesMaxSortInp)
if err != nil {
return
}
res = new(gencodes.MaxSortRes)
res.Sort = data.Sort
res.GenCodesMaxSortModel, err = service.SysGenCodes().MaxSort(ctx, &req.GenCodesMaxSortInp)
return
}

View File

@@ -26,13 +26,13 @@ func (a *cSite) Index(ctx context.Context, _ *base.SiteIndexReq) (res *base.Site
"version": consts.VersionApp,
}})
//err = gerror.New("这是一个测试错误")
//return
// err = gerror.New("这是一个测试错误")
// return
//err = gerror.NewCode(gcode.New(10000, "这是一个测试自定义错误码错误", nil))
//return
// err = gerror.NewCode(gcode.New(10000, "这是一个测试自定义错误码错误", nil))
// return
//service.View().Error(ctx, gerror.New("这是一个允许被自定义格式的错误,默认和通用错误格式一致,你可以修改它"))
//return
// service.View().Error(ctx, gerror.New("这是一个允许被自定义格式的错误,默认和通用错误格式一致,你可以修改它"))
// return
return
}

View File

@@ -137,9 +137,9 @@ func NewView(ctx context.Context, name string) *gview.View {
}
view.SetDelimiters(delimiters[0], delimiters[1])
//// 更多配置
//view.SetI18n()
//// ...
// 更多配置
// view.SetI18n()
// ...
return view
}

View File

@@ -3,7 +3,6 @@
// @Copyright Copyright (c) 2023 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package captcha
import (
@@ -17,21 +16,21 @@ import (
// Generate 生成验证码
func Generate(ctx context.Context) (id string, base64 string) {
// 字符
//driver := &base64Captcha.DriverString{
// Height: 42,
// Width: 100,
// //NoiseCount: 50,
// //ShowLineOptions: 20,
// Length: 4,
// BgColor: &color.RGBA{
// R: 255,
// G: 250,
// B: 250,
// A: 250,
// },
// Source: "0123456789", // abcdefghjkmnpqrstuvwxyz23456789
// Fonts: []string{"chromohv.ttf"},
//}
// driver := &base64Captcha.DriverString{
// Height: 42,
// Width: 100,
// //NoiseCount: 50,
// //ShowLineOptions: 20,
// Length: 4,
// BgColor: &color.RGBA{
// R: 255,
// G: 250,
// B: 250,
// A: 250,
// },
// Source: "0123456789", // abcdefghjkmnpqrstuvwxyz23456789
// Fonts: []string{"chromohv.ttf"},
// }
// 算数
driver := &base64Captcha.DriverMath{

View File

@@ -33,15 +33,15 @@ type EnumItem struct {
var standardPackages = make(map[string]struct{})
func init() {
stdPackages, err := packages.Load(nil, "std")
if err != nil {
panic(err)
}
for _, p := range stdPackages {
standardPackages[p.ID] = struct{}{}
}
}
//func init() {
// stdPackages, err := packages.Load(nil, "std")
// if err != nil {
// panic(err)
// }
// for _, p := range stdPackages {
// standardPackages[p.ID] = struct{}{}
// }
//}
func NewEnumsParser(prefixes []string) *EnumsParser {
return &EnumsParser{

View File

@@ -97,7 +97,6 @@ var defaultWhereModeMap = map[string]string{
// setDefault 设置默认属性
func setDefault(field *sysin.GenCodesColumnListModel) {
setDefaultEdit(field)
setDefaultFormMode(field)
@@ -192,7 +191,6 @@ func setDefaultFormMode(field *sysin.GenCodesColumnListModel) {
field.FormMode = FormModeInputEditor
return
}
}
// setDefaultFormRole 设置默认表单验证

View File

@@ -19,7 +19,7 @@ const (
LogicWhereComments = "\n\t// 查询%s\n"
LogicWhereNoSupport = "\t// TODO 暂不支持生成[ %s ]查询方式,请自行补充此处代码!"
LogicListSimpleSelect = "\tfields, err := hgorm.GenSelect(ctx, sysin.%sListModel{}, dao.%s)\n\tif err != nil {\n\t\treturn\n\t}"
LogicListJoinSelect = "\t//关联表select\n\tfields, err := hgorm.GenJoinSelect(ctx, %sin.%sListModel{}, &dao.%s, []*hgorm.Join{\n%v\t})\n\n\tif err != nil {\n\t\terr = gerror.Wrap(err, \"获取%s关联字段失败请稍后重试\")\n\t\treturn\n\t}"
LogicListJoinSelect = "\t// 关联表select\n\tfields, err := hgorm.GenJoinSelect(ctx, %sin.%sListModel{}, &dao.%s, []*hgorm.Join{\n%v\t})\n\n\tif err != nil {\n\t\terr = gerror.Wrap(err, \"获取%s关联字段失败请稍后重试\")\n\t\treturn\n\t}"
LogicListJoinOnRelation = "\t// 关联表%s\n\tmod = mod.%s(hgorm.GenJoinOnRelation(\n\t\tdao.%s.Table(), dao.%s.Columns().%s, // 主表表名,关联字段\n\t\tdao.%s.Table(), \"%s\", dao.%s.Columns().%s, // 关联表表名,别名,关联字段\n\t)...)\n\n"
LogicEditUpdate = "\tif _, err = s.Model(ctx%s).\n\t\t\tFields(%sin.%sUpdateFields{}).\n\t\t\tWherePri(in.%s).Data(in).Update(); err != nil {\n\t\t\terr = gerror.Wrap(err, \"修改%s失败请稍后重试\")\n\t\t}\n\t\treturn"
LogicEditInsert = "\tif _, err = s.Model(ctx, &handler.Option{FilterAuth: false}).\n\t\tFields(%sin.%sInsertFields{}).\n\t\tData(in).Insert(); err != nil {\n\t\terr = gerror.Wrap(err, \"新增%s失败请稍后重试\")\n\t}"

View File

@@ -56,12 +56,12 @@ func (l *gCurd) generateWebEditFormItem(ctx context.Context, in *CurdPreviewInpu
case FormModeDate:
component = fmt.Sprintf("<n-form-item label=\"%s\" path=\"%s\">\n <DatePicker v-model:formValue=\"params.%s\" type=\"date\" />\n </n-form-item>", field.Dc, field.TsName, field.TsName)
//case FormModeDateRange: // 必须要有两个字段,后面优化下
// case FormModeDateRange: // 必须要有两个字段,后面优化下
case FormModeTime:
component = fmt.Sprintf("<n-form-item label=\"%s\" path=\"%s\">\n <DatePicker v-model:formValue=\"params.%s\" type=\"datetime\" />\n </n-form-item>", field.Dc, field.TsName, field.TsName)
//case FormModeTimeRange: // 必须要有两个字段,后面优化下
// case FormModeTimeRange: // 必须要有两个字段,后面优化下
case FormModeRadio:
component = fmt.Sprintf("<n-form-item label=\"%s\" path=\"%s\">\n <n-radio-group v-model:value=\"params.%s\" name=\"%s\">\n <n-radio-button\n v-for=\"%s in options.%s\"\n :key=\"%s.value\"\n :value=\"%s.value\"\n :label=\"%s.label\"\n />\n </n-radio-group>\n </n-form-item>", field.Dc, field.TsName, field.TsName, field.TsName, field.TsName, in.options.dictMap[field.TsName], field.TsName, field.TsName, field.TsName)
@@ -109,7 +109,6 @@ func (l *gCurd) generateWebEditFormItem(ctx context.Context, in *CurdPreviewInpu
} else {
buffer.WriteString(" " + component + "\n\n")
}
}
return buffer.String()
}
@@ -167,7 +166,6 @@ func (l *gCurd) generateWebEditScript(ctx context.Context, in *CurdPreviewInput)
importBuffer.WriteString(" import CitySelector from '@/components/CitySelector/citySelector.vue';\n")
}
}
}
data["import"] = importBuffer.String()

View File

@@ -31,9 +31,9 @@ func (l *gCurd) webIndexTplData(ctx context.Context, in *CurdPreviewInput) (g.Ma
iconsImport = append(iconsImport, " PlusOutlined")
}
//// 编辑
//if in.options.Step.HasEdit {
//}
// 编辑
// if in.options.Step.HasEdit {
// }
// 导出
if in.options.Step.HasExport {

View File

@@ -31,7 +31,6 @@ func (l *gCurd) generateWebViewItem(ctx context.Context, in *CurdPreviewInput) s
)
switch field.FormMode {
case FormModeInputTextarea, FormModeInputEditor:
component = fmt.Sprintf("<n-descriptions-item>\n <template #label>%s</template>\n <span v-html=\"formValue.%s\"></span></n-descriptions-item>", field.Dc, field.TsName)

View File

@@ -206,7 +206,7 @@ func (client *Client) read() {
client.Close()
client.logger.Debugf(client.ctx, "client are about to be reconnected..")
time.Sleep(client.config.ConnectInterval)
client.Start()
_ = client.Start()
}()
if err := client.conn.Run(); err != nil {

View File

@@ -14,14 +14,13 @@ import (
// getCronKey 生成客户端定时任务名称
func (client *Client) getCronKey(s string) string {
return fmt.Sprintf("tcp.client_%s:%s", s, client.conn.LocalAddr().String())
return fmt.Sprintf("tcp.client_%s:%d", s, client.conn.CID)
}
// stopCron 停止定时任务
func (client *Client) stopCron() {
for _, v := range gcron.Entries() {
gcron.Remove(v.Name)
}
gcron.Remove(client.getCronKey(CronHeartbeatVerify))
gcron.Remove(client.getCronKey(CronHeartbeat))
}
// startCron 启动定时任务

View File

@@ -34,7 +34,6 @@ func (i *ServerRes) SetMessage(msg ...string) {
message := "操作成功"
if len(msg) > 0 {
message = msg[0]
return
}
i.Message = message
}
@@ -45,7 +44,6 @@ func (i *ServerRes) SetError(err error) {
i.Code = gerror.Code(err).Code()
i.Message = err.Error()
}
return
}
// GetError 获取响应中的错误

View File

@@ -90,7 +90,6 @@ func (m *MsgParser) RegisterRPCRouter(routers ...interface{}) (err error) {
// RegisterInterceptor 注册拦截器
func (m *MsgParser) RegisterInterceptor(interceptors ...Interceptor) {
m.interceptors = append(interceptors, interceptors...)
return
}
// Encoding 消息编码
@@ -166,7 +165,6 @@ func (m *MsgParser) doHandleRouterMsg(ctx context.Context, handler *RouteHandler
responseMsg, deErr := m.doDecoding(ctx, results[0].Interface(), msg.MsgId)
if deErr != nil && responseErr == nil {
responseErr = deErr
return
}
if responseErr != nil {

View File

@@ -203,7 +203,6 @@ func (server *Server) RegisterRouter(routers ...interface{}) {
if err != nil {
server.logger.Fatal(server.ctx, err)
}
return
}
// RegisterRPCRouter 注册RPC路由
@@ -212,7 +211,6 @@ func (server *Server) RegisterRPCRouter(routers ...interface{}) {
if err != nil {
server.logger.Fatal(server.ctx, err)
}
return
}
// RegisterInterceptor 注册拦截器

View File

@@ -19,16 +19,15 @@ func (server *Server) getCronKey(s string) string {
// stopCron 停止定时任务
func (server *Server) stopCron() {
for _, v := range gcron.Entries() {
gcron.Remove(v.Name)
}
gcron.Remove(server.getCronKey(CronHeartbeatVerify))
gcron.Remove(server.getCronKey(CronAuthVerify))
}
// startCron 启动定时任务
func (server *Server) startCron() {
// 心跳超时检查
if gcron.Search(server.getCronKey(CronHeartbeatVerify)) == nil {
gcron.AddSingleton(server.ctx, "@every 300s", func(ctx context.Context) {
_, _ = gcron.AddSingleton(server.ctx, "@every 300s", func(ctx context.Context) {
if server == nil || server.clients == nil {
return
}
@@ -43,7 +42,7 @@ func (server *Server) startCron() {
// 认证检查
if gcron.Search(server.getCronKey(CronAuthVerify)) == nil {
gcron.AddSingleton(server.ctx, "@every 300s", func(ctx context.Context) {
_, _ = gcron.AddSingleton(server.ctx, "@every 300s", func(ctx context.Context) {
if server == nil || server.clients == nil {
return
}
@@ -52,7 +51,7 @@ func (server *Server) startCron() {
continue
}
if client.Auth.EndAt.Before(gtime.Now()) {
client.Conn.Close()
_ = client.Conn.Close()
server.logger.Debugf(server.ctx, "client auth expired, close conn. auth:%+v", client.Auth)
}
}

View File

@@ -18,7 +18,7 @@ func NewShareChatMessage() *ShareChatMessage {
return &ShareChatMessage{}
}
func (m *ShareChatMessage) SetShareChatID(ID string) *ShareChatMessage {
m.Content.ShareChatID = ID
func (m *ShareChatMessage) SetShareChatID(id string) *ShareChatMessage {
m.Content.ShareChatID = id
return m
}

View File

@@ -114,7 +114,6 @@ func AutoTradeType(payType, userAgent string) (tradeType string) {
}
return consts.TradeTypeQQWeb
default:
}
return
}

View File

@@ -5,24 +5,24 @@ import (
"sync"
)
// consumerStrategy 消费者策略,实现该接口即可加入到消费队列中
type consumerStrategy interface {
// Consumer 消费者接口,实现该接口即可加入到消费队列中
type Consumer interface {
GetTopic() string // 获取消费主题
Handle(ctx context.Context, mqMsg MqMsg) (err error) // 处理消息
Handle(ctx context.Context, mqMsg MqMsg) (err error) // 处理消息的方法
}
// consumerManager 消费者管理
type consumerManager struct {
sync.Mutex
list map[string]consumerStrategy // 维护的消费者列表
list map[string]Consumer // 维护的消费者列表
}
var consumers = &consumerManager{
list: make(map[string]consumerStrategy),
list: make(map[string]Consumer),
}
// RegisterConsumer 注册任务到消费者队列
func RegisterConsumer(cs consumerStrategy) {
func RegisterConsumer(cs Consumer) {
consumers.Lock()
defer consumers.Unlock()
topic := cs.GetTopic()
@@ -35,18 +35,18 @@ func RegisterConsumer(cs consumerStrategy) {
// StartConsumersListener 启动所有已注册的消费者监听
func StartConsumersListener(ctx context.Context) {
for _, consumer := range consumers.list {
go func(consumer consumerStrategy) {
consumerListen(ctx, consumer)
}(consumer)
for _, c := range consumers.list {
go func(c Consumer) {
consumerListen(ctx, c)
}(c)
}
}
// consumerListen 消费者监听
func consumerListen(ctx context.Context, job consumerStrategy) {
func consumerListen(ctx context.Context, job Consumer) {
var (
topic = job.GetTopic()
consumer, err = InstanceConsumer()
topic = job.GetTopic()
c, err = InstanceConsumer()
)
if err != nil {
@@ -54,17 +54,16 @@ func consumerListen(ctx context.Context, job consumerStrategy) {
return
}
if listenErr := consumer.ListenReceiveMsgDo(topic, func(mqMsg MqMsg) {
if listenErr := c.ListenReceiveMsgDo(topic, func(mqMsg MqMsg) {
err = job.Handle(ctx, mqMsg)
//if err != nil {
// if err != nil {
// // 遇到错误,重新加入到队列
// //queue.Push(topic, mqMsg.Body)
//}
// }
// 记录消费队列日志
ConsumerLog(ctx, topic, mqMsg, err)
}); listenErr != nil {
Logger().Fatalf(ctx, "消费队列:%s 监听失败, err:%+v", topic, listenErr)
}

View File

@@ -117,8 +117,9 @@ func (r *reader) close() {
// sync index and offset
func (r *reader) sync() {
name := path.Join(r.config.Path, indexFile)
data, _ := json.Marshal(&r.checkpoint)
_ = os.WriteFile(name, data, filePerm)
if data, err := json.Marshal(&r.checkpoint); err == nil {
_ = os.WriteFile(name, data, filePerm)
}
}
// restore index and offset

View File

@@ -85,7 +85,7 @@ func (r *KafkaMq) ListenReceiveMsgDo(topic string, receiveDo func(mqMsg MqMsg))
return gerror.New("queue kafka consumer not register")
}
consumer := Consumer{
consumer := KaConsumer{
ready: make(chan bool),
receiveDoFun: receiveDo,
}
@@ -219,26 +219,25 @@ func validateVersion(version sarama.KafkaVersion) bool {
return false
}
type Consumer struct {
type KaConsumer struct {
ready chan bool
receiveDoFun func(mqMsg MqMsg)
}
// Setup is run at the beginning of a new session, before ConsumeClaim
func (consumer *Consumer) Setup(sarama.ConsumerGroupSession) error {
func (consumer *KaConsumer) Setup(sarama.ConsumerGroupSession) error {
// Mark the consumer as ready
close(consumer.ready)
return nil
}
// Cleanup is run at the end of a session, once all ConsumeClaim goroutines have exited
func (consumer *Consumer) Cleanup(sarama.ConsumerGroupSession) error {
func (consumer *KaConsumer) Cleanup(sarama.ConsumerGroupSession) error {
return nil
}
// ConsumeClaim must start a consumer loop of ConsumerGroupClaim's Messages().
func (consumer *Consumer) ConsumeClaim(session sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error {
func (consumer *KaConsumer) ConsumeClaim(session sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error {
// NOTE:
// Do not move the code below to a goroutine.
// The `ConsumeClaim` itself is called within a goroutine, see:

View File

@@ -85,14 +85,14 @@ func (d *TencentDrive) SendCode(ctx context.Context, in *sysin.SendCodeInp) (err
* 示例如:+8613711112222 其中前面有一个+号 86为国家码13711112222为手机号最多不要超过200个手机号*/
request.PhoneNumberSet = common.StringPtrs([]string{fmt.Sprintf("+86%v", in.Mobile)})
///* 用户的 session 内容(无需要可忽略): 可以携带用户侧 ID 等上下文信息server 会原样返回 */
//request.SessionContext = common.StringPtr("")
//
///* 短信码号扩展号(无需要可忽略): 默认未开通,如需开通请联系 [腾讯云短信小助手] */
//request.ExtendCode = common.StringPtr("")
//
///* 国际/港澳台短信 SenderId无需要可忽略: 国内短信填空,默认未开通,如需开通请联系 [腾讯云短信小助手] */
//request.SenderId = common.StringPtr("")
/* 用户的 session 内容(无需要可忽略): 可以携带用户侧 ID 等上下文信息server 会原样返回 */
// request.SessionContext = common.StringPtr("")
/* 短信码号扩展号(无需要可忽略): 默认未开通,如需开通请联系 [腾讯云短信小助手] */
// request.ExtendCode = common.StringPtr("")
/* 国际/港澳台短信 SenderId无需要可忽略: 国内短信填空,默认未开通,如需开通请联系 [腾讯云短信小助手] */
// request.SenderId = common.StringPtr("")
// 通过client对象调用想要访问的接口需要传入请求对象
response, err := client.SendSms(request)

View File

@@ -206,8 +206,8 @@ func (s *sAdminOrder) Create(ctx context.Context, in *adminin.OrderCreateInp) (r
// 读取商品信息,读取商品最终支付价格
// ...
//in.Money = 999
//subject = fmt.Sprintf("购买商品:%v", "测试商品名称")
// in.Money = 999
// subject = fmt.Sprintf("购买商品:%v", "测试商品名称")
default:
err = gerror.New("不支持的订单类型")
@@ -290,7 +290,7 @@ func (s *sAdminOrder) List(ctx context.Context, in *adminin.OrderListInp) (list
return
}
//关联表select
// 关联表select
fields, err := hgorm.GenJoinSelect(ctx, adminin.OrderListModel{}, &dao.AdminOrder, []*hgorm.Join{
{Dao: &dao.PayLog, Alias: "payLog"},
})

View File

@@ -112,19 +112,6 @@ func (s *sSysAddonsConfig) UpdateConfigByGroup(ctx context.Context, in *sysin.Up
row := s.getConfigByKey(k, models)
// 新增
if row == nil {
//row.Id = 0
//row.Key = k
//row.Value = gconv.String(v)
//row.Group = in.Group
//row.Status = consts.StatusEnabled
//row.CreatedAt = gtime.Now()
//row.UpdatedAt = gtime.Now()
//_, err := dao.SysAddonsConfig.Ctx(ctx).Data(row).Insert()
//if err != nil {
// err = gerror.Wrap(err, consts.ErrorORM)
// return err
//}
//continue
return gerror.Newf("暂不支持从前台添加变量,请先在数据库表[%v]中配置变量:%v", dao.SysAddonsConfig.Table(), k)
}

View File

@@ -249,19 +249,6 @@ func (s *sSysConfig) UpdateConfigByGroup(ctx context.Context, in *sysin.UpdateCo
row := s.getConfigByKey(k, models)
// 新增
if row == nil {
//row.Id = 0
//row.Key = k
//row.Value = gconv.String(v)
//row.Group = in.Group
//row.Status = consts.StatusEnabled
//row.CreatedAt = gtime.Now()
//row.UpdatedAt = gtime.Now()
//_, err := dao.SysConfig.Ctx(ctx).Data(row).Insert()
//if err != nil {
// err = gerror.Wrap(err, consts.ErrorORM)
// return err
//}
//continue
err = gerror.Newf("暂不支持从前台添加变量,请先在数据库表[%v]中配置变量:%v", dao.SysConfig.Table(), k)
return
}

View File

@@ -82,7 +82,7 @@ func (s *sSysCurdDemo) List(ctx context.Context, in *sysin.CurdDemoListInp) (lis
return
}
//关联表select
// 关联表select
fields, err := hgorm.GenJoinSelect(ctx, sysin.CurdDemoListModel{}, &dao.SysGenCurdDemo, []*hgorm.Join{
{Dao: &dao.TestCategory, Alias: "testCategory"},
})

View File

@@ -7,7 +7,6 @@ package sys
import (
"context"
"encoding/json"
"github.com/gogf/gf/v2/encoding/gjson"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g"
@@ -168,7 +167,8 @@ func (s *sSysLog) AnalysisLog(ctx context.Context) entity.SysLog {
}
// 请求头
if reqHeadersBytes, _ := json.Marshal(request.Header); len(gconv.String(reqHeadersBytes)) > 0 {
if reqHeadersBytes, _ := gjson.New(request.Header).MarshalJSON(); len(reqHeadersBytes) > 0 {
headerData = gjson.New(reqHeadersBytes)
}
@@ -322,26 +322,13 @@ func (s *sSysLog) List(ctx context.Context, in *sysin.LogListInp) (list []*sysin
list[i].MemberName = memberName.String()
}
//// 接口
//if list[i].AppId == consts.AppApi {
// //memberName, err = dao.Member.Ctx(ctx).Fields("realname").Where("id", res.List[i].MemberId).Value()
// //if err != nil {
// // err = gerror.Wrap(err, consts.ErrorORM)
// // return nil, err
// //}
//}
// 接口
// ...
if list[i].MemberName == "" {
list[i].MemberName = "游客"
}
//// 获取省市编码对应的地区名称
//region, err := dao.SysProvinces.GetRegion(ctx, list[i].ProvinceId, list[i].CityId)
//if err != nil {
// return list, totalCount, err
//}
//list[i].Region = region
// 截取请求url路径
if gstr.Contains(list[i].Url, "?") {
list[i].Url = gstr.StrTillEx(list[i].Url, "?")
@@ -354,7 +341,6 @@ func (s *sSysLog) List(ctx context.Context, in *sysin.LogListInp) (list []*sysin
]
}`)
}
}
return
}

View File

@@ -83,7 +83,7 @@ func (s *sSysLoginLog) List(ctx context.Context, in *sysin.LoginLogListInp) (lis
return
}
//关联表select
// 关联表select
fields, err := hgorm.GenJoinSelect(ctx, sysin.LoginLogListModel{}, &dao.SysLoginLog, []*hgorm.Join{
{Dao: &dao.SysLog, Alias: "sysLog"},
})
@@ -98,12 +98,6 @@ func (s *sSysLoginLog) List(ctx context.Context, in *sysin.LoginLogListInp) (lis
}
for _, v := range list {
//// 获取省市编码对应的地区名称
//region, err := location.ParseRegion(ctx, v.SysLogProvinceId, v.SysLogCityId, 0)
//if err != nil {
// return list, totalCount, err
//}
//v.Region = region
v.Os = useragent.GetOs(v.SysLogUserAgent)
v.Browser = useragent.GetBrowser(v.SysLogUserAgent)
}

View File

@@ -72,7 +72,7 @@ func (s *sSysServeLog) List(ctx context.Context, in *sysin.ServeLogListInp) (lis
return
}
//关联表select
// 关联表select
fields, err := hgorm.GenJoinSelect(ctx, sysin.ServeLogListModel{}, &dao.SysServeLog, []*hgorm.Join{
{Dao: &dao.SysLog, Alias: "sysLog"},
})

View File

@@ -96,7 +96,7 @@ func (s *sAuthClient) onLoginEvent() {
ctx := gctx.New()
// 获取授权信息
s.client.Send(ctx, &servmsg.AuthSummaryReq{})
_ = s.client.Send(ctx, &servmsg.AuthSummaryReq{})
// 测试例子,实际使用时可以注释掉
s.testExample(ctx)

View File

@@ -36,7 +36,7 @@ func (s *sAuthClient) OnResponseExampleHello(ctx context.Context, req *servmsg.E
func (s *sAuthClient) testExample(ctx context.Context) {
// 发起tcp请求
// 异步执行,服务端返回消息后会转到`OnResponseExampleHello`中
s.client.Send(ctx, &servmsg.ExampleHelloReq{
_ = s.client.Send(ctx, &servmsg.ExampleHelloReq{
Name: "Tom",
})

View File

@@ -12,7 +12,7 @@ import (
// DefaultInterceptor 默认拦截器
func (s *sCronClient) DefaultInterceptor(ctx context.Context, msg *tcp.Message) (err error) {
//conn := tcp.ConnFromCtx(ctx)
//g.Log().Debugf(ctx, "DefaultInterceptor msg:%+v, conn:%+v", msg, gjson.New(conn).String())
// conn := tcp.ConnFromCtx(ctx)
// g.Log().Debugf(ctx, "DefaultInterceptor msg:%+v, conn:%+v", msg, gjson.New(conn).String())
return
}

View File

@@ -34,37 +34,37 @@ func (s *sTCPServer) OnAuthSummary(ctx context.Context, req *servmsg.AuthSummary
if conn.Auth == nil {
res.SetError(gerror.New("登录信息获取失败,请重新登录"))
conn.Send(ctx, res)
_ = conn.Send(ctx, res)
return
}
if err := dao.SysServeLicense.Ctx(ctx).Where("appid = ?", conn.Auth.AppId).Scan(&models); err != nil {
res.SetError(err)
conn.Send(ctx, res)
_ = conn.Send(ctx, res)
return
}
if models == nil {
res.SetError(gerror.New("授权信息不存在"))
conn.Send(ctx, res)
_ = conn.Send(ctx, res)
return
}
if models.Status != consts.StatusEnabled {
res.SetError(gerror.New("授权已禁用,请联系管理员"))
conn.Send(ctx, res)
_ = conn.Send(ctx, res)
return
}
if models.Group != conn.Auth.Group {
res.SetError(gerror.New("你登录的授权分组未得到授权,请联系管理员"))
conn.Send(ctx, res)
_ = conn.Send(ctx, res)
return
}
if models.EndAt.Before(gtime.Now()) {
res.SetError(gerror.New("授权已过期,请联系管理员"))
conn.Send(ctx, res)
_ = conn.Send(ctx, res)
return
}
@@ -76,5 +76,5 @@ func (s *sTCPServer) OnAuthSummary(ctx context.Context, req *servmsg.AuthSummary
// ...
res.Data = data
conn.Send(ctx, res)
_ = conn.Send(ctx, res)
}

View File

@@ -27,14 +27,14 @@ func (s *sTCPServer) OnExampleHello(ctx context.Context, req *servmsg.ExampleHel
if conn.Auth == nil {
res.SetError(gerror.New("连接未认证,请确认已登录成功!"))
conn.Send(ctx, res)
_ = conn.Send(ctx, res)
return
}
data.Desc = fmt.Sprintf("Hello %v, 你的APPID%v当前HotGo版本%v你成功请求了`servmsg.ExampleHelloReq`接口!", req.Name, conn.Auth.AppId, consts.VersionApp)
data.Timestamp = gtime.Now()
res.Data = data
conn.Send(ctx, res)
_ = conn.Send(ctx, res)
}
// OnExampleRPCHello 一个rpc请求例子

View File

@@ -39,7 +39,7 @@ func (s *sTCPServer) onServerLogin(ctx context.Context, req *tcp.ServerLoginReq)
}
if models == nil {
res.SetError(gerror.New("授权信息不存在"))
conn.Send(ctx, res)
_ = conn.Send(ctx, res)
return
}
@@ -47,39 +47,39 @@ func (s *sTCPServer) onServerLogin(ctx context.Context, req *tcp.ServerLoginReq)
sign := encrypt.Md5ToString(fmt.Sprintf("%v%v%v", models.Appid, req.Timestamp, models.SecretKey))
if sign != req.Sign {
res.SetError(gerror.New("签名错误,请检查!"))
conn.Send(ctx, res)
_ = conn.Send(ctx, res)
return
}
if models.Status != consts.StatusEnabled {
res.SetError(gerror.New("授权已禁用,请联系管理员"))
conn.Send(ctx, res)
_ = conn.Send(ctx, res)
return
}
if models.Group != req.Group {
res.SetError(gerror.New("你登录的授权分组未得到授权,请联系管理员"))
conn.Send(ctx, res)
_ = conn.Send(ctx, res)
return
}
if models.EndAt.Before(gtime.Now()) {
res.SetError(gerror.New("授权已过期,请联系管理员"))
conn.Send(ctx, res)
_ = conn.Send(ctx, res)
return
}
ip := gstr.StrTillEx(conn.RemoteAddr().String(), ":")
if !convert.MatchIpStrategy(models.AllowedIps, ip) {
res.SetError(gerror.New("IP(" + ip + ")未授权,请联系管理员"))
conn.Send(ctx, res)
_ = conn.Send(ctx, res)
return
}
var routes []string
if err := models.Routes.Scan(&routes); err != nil {
res.SetError(gerror.New("授权路由解析失败,请联系管理员"))
conn.Send(ctx, res)
_ = conn.Send(ctx, res)
return
}
@@ -92,14 +92,14 @@ func (s *sTCPServer) onServerLogin(ctx context.Context, req *tcp.ServerLoginReq)
client.Close()
}
res.SetError(gerror.New("授权登录端超出上限,请勿多地登录"))
conn.Send(ctx, res)
_ = conn.Send(ctx, res)
return
}
for _, client := range clients {
if client.Auth.Name == req.Name {
res.SetError(gerror.Newf("应用名称[%v]已存在登录用户,当前连接已被拒绝。", req.Name))
conn.Send(ctx, res)
_ = conn.Send(ctx, res)
return
}
}
@@ -123,12 +123,12 @@ func (s *sTCPServer) onServerLogin(ctx context.Context, req *tcp.ServerLoginReq)
}
if _, err := dao.SysServeLicense.Ctx(ctx).Where(cols.Id, models.Id).Data(update).Update(); err != nil {
res.SetError(err)
conn.Send(ctx, res)
_ = conn.Send(ctx, res)
return
}
g.Log().Debugf(ctx, "onServerLogin succeed. appid:%v, group:%v, name:%v", auth.AppId, auth.Group, auth.Name)
conn.Send(ctx, res)
_ = conn.Send(ctx, res)
}
// onServerHeartbeat 处理客户端心跳
@@ -146,7 +146,7 @@ func (s *sTCPServer) onServerHeartbeat(ctx context.Context, req *tcp.ServerHeart
client := s.serv.GetClient(conn.Conn)
if client == nil {
res.SetError(gerror.New("登录异常,请重新登录"))
conn.Send(ctx, res)
_ = conn.Send(ctx, res)
return
}
@@ -159,9 +159,9 @@ func (s *sTCPServer) onServerHeartbeat(ctx context.Context, req *tcp.ServerHeart
}
if _, err := dao.SysServeLicense.Ctx(ctx).Where(dao.SysServeLicense.Columns().Appid, client.Auth.AppId).Data(update).Update(); err != nil {
res.SetError(err)
conn.Send(ctx, res)
_ = conn.Send(ctx, res)
return
}
conn.Send(ctx, res)
_ = conn.Send(ctx, res)
}

View File

@@ -37,7 +37,7 @@ func (s *sTCPServer) isNoVerifyRouter(router string) bool {
// DefaultInterceptor 默认拦截器
func (s *sTCPServer) DefaultInterceptor(ctx context.Context, msg *tcp.Message) (err error) {
conn := tcp.ConnFromCtx(ctx)
//g.Log().Debugf(ctx, "DefaultInterceptor msg:%+v, conn:%+v", msg, gjson.New(conn).String())
// g.Log().Debugf(ctx, "DefaultInterceptor msg:%+v, conn:%+v", msg, gjson.New(conn).String())
// 免登录
if s.isNoLoginRouter(msg.Router) {
@@ -70,6 +70,6 @@ func (s *sTCPServer) DefaultInterceptor(ctx context.Context, msg *tcp.Message) (
// PreFilterInterceptor 预处理
func (s *sTCPServer) PreFilterInterceptor(ctx context.Context, msg *tcp.Message) (err error) {
//g.Log().Debug(ctx, "PreFilterInterceptor...")
// g.Log().Debug(ctx, "PreFilterInterceptor...")
return
}

View File

@@ -14,7 +14,7 @@ type GenCodesColumn struct {
Index string `json:"index" dc:"索引"`
Extra string `json:"extra" dc:"额外选项"`
// 自定义生成属性
//Alias string `json:"alias" dc:"字段别名"`
// Alias string `json:"alias" dc:"字段别名"`
GoName string `json:"goName" dc:"Go属性"`
GoType string `json:"goType" dc:"Go类型"`
TsName string `json:"tsName" dc:"Ts属性"`

View File

@@ -85,7 +85,7 @@ type MenuListModel struct {
type MenuRouteMeta struct {
// 解释参考https://naive-ui-admin-docs.vercel.app/guide/router.html#%E5%A4%9A%E7%BA%A7%E8%B7%AF%E7%94%B1
Title string `json:"title"` // 菜单名称 一般必填
//Disabled bool `json:"disabled,omitempty"` // 禁用菜单
// Disabled bool `json:"disabled,omitempty"` // 禁用菜单
Icon string `json:"icon,omitempty"` // 菜单图标
KeepAlive bool `json:"keepAlive,omitempty"` // 缓存该路由
Hidden bool `json:"hidden,omitempty"` // 隐藏菜单

View File

@@ -25,7 +25,7 @@ type ServeLicenseUpdateFields struct {
Appid string `json:"appid" dc:"应用ID"`
SecretKey string `json:"secretKey" dc:"应用秘钥"`
OnlineLimit int `json:"onlineLimit" dc:"在线数量限制默认1"`
//Routes *gjson.Json `json:"routes" dc:"路由表,空使用默认分组路由"`
// Routes *gjson.Json `json:"routes" dc:"路由表,空使用默认分组路由"`
AllowedIps string `json:"allowedIps" dc:"白名单,*代表所有只有允许的IP才能连接到tcp服务"`
EndAt *gtime.Time `json:"endAt" dc:"授权结束时间"`
Remark string `json:"remark" dc:"备注"`
@@ -39,7 +39,7 @@ type ServeLicenseInsertFields struct {
Appid string `json:"appid" dc:"应用ID"`
SecretKey string `json:"secretKey" dc:"应用秘钥"`
OnlineLimit int `json:"onlineLimit" dc:"在线数量限制默认1"`
//Routes *gjson.Json `json:"routes" dc:"路由表,空使用默认分组路由"`
// Routes *gjson.Json `json:"routes" dc:"路由表,空使用默认分组路由"`
AllowedIps string `json:"allowedIps" dc:"白名单,*代表所有只有允许的IP才能连接到tcp服务"`
EndAt *gtime.Time `json:"endAt" dc:"授权结束时间"`
Remark string `json:"remark" dc:"备注"`

View File

@@ -105,9 +105,9 @@ func (manager *ClientManager) DelClients(client *Client) {
}
// GetClient 通过socket ID获取客户端的连接
func (manager *ClientManager) GetClient(ID string) (client *Client) {
func (manager *ClientManager) GetClient(id string) (client *Client) {
for c := range manager.Clients {
if c.ID == ID {
if c.ID == id {
return c
}
}
@@ -164,8 +164,8 @@ func (manager *ClientManager) EventRegister(client *Client) {
UserId: client.User.Id,
Client: client,
})
////发送当前客户端标识
//SendSuccess(client, "connected", g.Map{"id": client.ID, "userInfo": client.User})
// 发送当前客户端标识
// SendSuccess(client, "connected", g.Map{"id": client.ID, "userInfo": client.User})
}
// EventLogin 用户登录事件
@@ -196,7 +196,6 @@ func (manager *ClientManager) clearTimeoutConnections() {
clients := clientManager.GetClients()
for client := range clients {
if client.IsHeartbeatTimeout(currentTime) {
//fmt.Println("心跳时间超时 关闭连接", client.Addr, client.UserId, client.LoginTime, client.HeartbeatTime)
_ = client.Socket.Close()
}
}
@@ -210,14 +209,16 @@ func (manager *ClientManager) ping() {
return
}
}()
////定时任务,发送心跳包
//gcron.Add(ctx, "0 */1 * * * *", func(ctx context.Context) {
// 定时任务,发送心跳包
// gcron.Add(ctx, "0 */1 * * * *", func(ctx context.Context) {
// res := &WResponse{
// Event: "ping",
// Timestamp: gtime.Now().Unix(),
// }
// SendToAll(res)
//})
// Timestamp: gtime.Now().Unix(),
// }
// SendToAll(res)
// })
// 定时任务,清理超时连接
_, _ = gcron.Add(ctxManager, "*/30 * * * * *", func(ctx context.Context) {
manager.clearTimeoutConnections()

View File

@@ -36,5 +36,4 @@ func WebSocket(ctx context.Context, group *ghttp.RouterGroup) {
ws.RegisterMsg(ws.EventHandlers{
// ...
})
}

View File

@@ -12,37 +12,38 @@ import (
"path/filepath"
)
type fileInfo struct { //文件信息
// 文件信息
type fileInfo struct {
name string
size int64
}
// WalkDir 递归获取目录下文件的名称和大小
func WalkDir(dirname string) (error, []fileInfo) {
op, err := filepath.Abs(dirname) //获取目录的绝对路径
op, err := filepath.Abs(dirname) // 获取目录的绝对路径
if nil != err {
return err, nil
}
files, err := os.ReadDir(op) //获取目录下所有文件的信息,包括文件和文件夹
files, err := os.ReadDir(op) // 获取目录下所有文件的信息,包括文件和文件夹
if nil != err {
return err, nil
}
var fileInfos []fileInfo //返回值,存储读取的文件信息
var fileInfos []fileInfo // 返回值,存储读取的文件信息
for _, f := range files {
if f.IsDir() { // 如果是目录,那么就递归调用
err, fs := WalkDir(op + `/` + f.Name()) //路径分隔符linux 和 windows 不同
err, fs := WalkDir(op + `/` + f.Name()) // 路径分隔符linux 和 windows 不同
if nil != err {
return err, nil
}
fileInfos = append(fileInfos, fs...) //将 slice 添加到 slice
fileInfos = append(fileInfos, fs...) // 将 slice 添加到 slice
} else {
info, err := f.Info()
if nil != err {
return err, nil
}
fi := fileInfo{op + `/` + f.Name(), info.Size()}
fileInfos = append(fileInfos, fi) //slice 中添加成员
fileInfos = append(fileInfos, fi) // slice 中添加成员
}
}
return nil, fileInfos

View File

@@ -32,8 +32,8 @@ func GenLabel(basic string, appendId int64) string {
}
// GetIdLabel 获取指定Id的树标签
func GetIdLabel(Id int64) string {
return fmt.Sprintf("%v%v%v", treeBeginCut, Id, treeEndCut)
func GetIdLabel(id int64) string {
return fmt.Sprintf("%v%v%v", treeBeginCut, id, treeEndCut)
}
// GetIds 获取上级ID集合

View File

@@ -0,0 +1,68 @@
package validate_test
import (
"context"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/test/gtest"
"hotgo/utility/validate"
"testing"
)
// MockFilter 是 Filter 接口的模拟实现。
type MockFilter struct {
Foo string
Bar int
}
func (f *MockFilter) Filter(ctx context.Context) error {
// 模拟过滤逻辑
// 过滤出错的例子
if f.Foo == "" {
return gerror.New("Foo 字段是必需的")
}
// 过滤操作的例子
f.Bar += 10
return nil
}
func TestPreFilter(t *testing.T) {
ctx := context.Background()
input := &MockFilter{
Foo: "test",
Bar: 5,
}
err := validate.PreFilter(ctx, input)
gtest.C(t, func(t *gtest.T) {
t.AssertNil(err)
})
t.Logf("input:%+v", input)
// 验证过滤结果
expectedBar := 15
gtest.C(t, func(t *gtest.T) {
t.Assert(input.Bar, expectedBar)
})
}
func TestPreFilter_Error(t *testing.T) {
ctx := context.Background()
input := &MockFilter{
Foo: "",
Bar: 5,
}
err := validate.PreFilter(ctx, input)
gtest.C(t, func(t *gtest.T) {
t.AssertNE(err, nil)
})
expectedError := "Foo 字段是必需的"
gtest.C(t, func(t *gtest.T) {
t.Assert(err.Error(), expectedError)
})
}

View File

@@ -42,15 +42,15 @@ func IsIp(ip string) bool {
}
// IsPublicIp 是否是公网IP
func IsPublicIp(Ip string) bool {
ip := net.ParseIP(Ip)
func IsPublicIp(ip string) bool {
i := net.ParseIP(ip)
if ip.IsLoopback() || ip.IsPrivate() || ip.IsMulticast() || ip.IsUnspecified() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() {
if i.IsLoopback() || i.IsPrivate() || i.IsMulticast() || i.IsUnspecified() || i.IsLinkLocalUnicast() || i.IsLinkLocalMulticast() {
return false
}
if ip4 := ip.To4(); ip4 != nil {
return !ip.Equal(net.IPv4bcast)
if ip4 := i.To4(); ip4 != nil {
return !i.Equal(net.IPv4bcast)
}
return true
}
@@ -89,7 +89,7 @@ func IsMobile(mobile string) bool {
// IsEmail 是否为邮箱地址
func IsEmail(email string) bool {
//pattern := `\w+([-+.]\w+)@\w+([-.]\w+).\w+([-.]\w+)*` //匹配电子邮箱
// pattern := `\w+([-+.]\w+)@\w+([-.]\w+).\w+([-.]\w+)*` //匹配电子邮箱
pattern := `^[0-9a-z][_.0-9a-z-]{0,31}@([0-9a-z][0-9a-z-]{0,30}[0-9a-z].){1,4}[a-z]{2,4}$`
reg := regexp.MustCompile(pattern)
return reg.MatchString(email)