From 4b8edb462420c73298ee5dae9ed90ce2a7adb852 Mon Sep 17 00:00:00 2001 From: 1379 <1379@1379.com> Date: Sat, 7 Jan 2023 23:50:13 +0800 Subject: [PATCH] fix: lint error --- .github/workflows/linter.yml | 2 +- .../linters/.golangci.yml => .golangci.yml | 34 +++--- cmd/generate/generate.go | 2 +- config/config.go | 2 +- consts/consts.go | 2 +- consts/enum.go | 102 ++++++++++-------- dal/dal.go | 2 + event/events.go | 2 +- event/listener/log.go | 2 +- event/listener/template_config.go | 2 +- handler/admin/admin.go | 11 +- handler/admin/backup.go | 19 ++-- handler/admin/category.go | 13 ++- handler/admin/comment_journal.go | 8 +- handler/admin/comment_post.go | 8 +- handler/admin/comment_sheet.go | 4 +- handler/admin/install.go | 5 +- handler/admin/journal.go | 10 +- handler/admin/link.go | 8 +- handler/admin/menu.go | 14 ++- handler/admin/photo.go | 8 +- handler/admin/post.go | 17 +-- handler/admin/sheet.go | 24 +++-- handler/admin/tag.go | 8 +- handler/admin/theme.go | 26 +++-- handler/admin/user.go | 16 ++- handler/binding/form_binding.go | 9 +- handler/binding/form_mapping.go | 6 +- handler/content/api/sheet.go | 46 ++++---- .../authentication/category_authentication.go | 14 +-- .../authentication/post_authentication.go | 11 +- handler/content/model/journal.go | 1 - handler/content/model/photo.go | 1 - handler/content/model/post.go | 10 +- handler/content/model/sheet.go | 10 +- handler/content/model/tag.go | 1 - handler/middleware/log.go | 9 +- handler/middleware/recovery.go | 2 + handler/route.go | 16 +-- handler/server.go | 12 +-- handler/trans/trans.go | 2 +- log/log.go | 4 +- main.go | 1 - model/dto/comment.go | 2 +- model/param/install.go | 2 +- model/property/attachment.go | 2 +- model/property/base.go | 8 +- model/property/blog.go | 2 +- model/property/comment.go | 2 +- model/property/other.go | 2 +- model/property/primary_property.go | 2 +- model/vo/mfa.go | 2 +- service/assembler/comment_base.go | 4 +- service/backup.go | 2 +- service/impl/admin.go | 8 +- service/impl/attachment.go | 27 ++--- service/impl/backup.go | 9 +- service/impl/base_post.go | 11 +- service/impl/category.go | 14 ++- service/impl/client_option.go | 4 +- service/impl/comment_base.go | 2 +- service/impl/comment_post.go | 3 +- service/impl/common.go | 12 ++- service/impl/export_import.go | 2 +- service/impl/init.go | 4 +- service/impl/install.go | 6 +- service/impl/log.go | 3 +- service/impl/option.go | 14 +-- service/impl/post.go | 39 ++++--- service/impl/sheet.go | 4 +- service/impl/tag.go | 10 +- service/impl/theme.go | 14 +-- service/option.go | 2 +- .../impl}/aliyun.go | 2 +- .../impl}/common.go | 2 +- .../impl}/file_descriptor.go | 2 +- .../impl}/init.go | 2 +- .../impl}/local.go | 10 +- .../impl}/minio.go | 2 +- .../impl}/url_file_descriptor.go | 2 +- .../file_storage.go => storage/storage.go} | 12 +-- service/theme/property_scanner.go | 30 ++++-- service/theme/theme_fetcher.go | 3 +- template/extension/post.go | 8 +- template/extension/tool.go | 5 +- template/template.go | 39 ++----- template/watcher.go | 8 +- util/common.go | 6 +- util/conv.go | 2 +- util/file.go | 39 ++++--- util/haloerr/error.go | 12 ++- util/rainbow_page.go | 9 +- util/xerr/error.go | 12 ++- 93 files changed, 507 insertions(+), 424 deletions(-) rename .github/linters/.golangci.yml => .golangci.yml (74%) rename service/{file_storage/file_storage_impl => storage/impl}/aliyun.go (99%) rename service/{file_storage/file_storage_impl => storage/impl}/common.go (98%) rename service/{file_storage/file_storage_impl => storage/impl}/file_descriptor.go (99%) rename service/{file_storage/file_storage_impl => storage/impl}/init.go (83%) rename service/{file_storage/file_storage_impl => storage/impl}/local.go (96%) rename service/{file_storage/file_storage_impl => storage/impl}/minio.go (99%) rename service/{file_storage/file_storage_impl => storage/impl}/url_file_descriptor.go (98%) rename service/{file_storage/file_storage.go => storage/storage.go} (71%) diff --git a/.github/workflows/linter.yml b/.github/workflows/linter.yml index 36d020b..76f30ba 100644 --- a/.github/workflows/linter.yml +++ b/.github/workflows/linter.yml @@ -28,5 +28,5 @@ jobs: uses: golangci/golangci-lint-action@v3 with: version: latest - args: --config=.github/linters/.golangci.yml + args: --config=.golangci.yml only-new-issues: true diff --git a/.github/linters/.golangci.yml b/.golangci.yml similarity index 74% rename from .github/linters/.golangci.yml rename to .golangci.yml index b788126..d1eabb7 100644 --- a/.github/linters/.golangci.yml +++ b/.golangci.yml @@ -6,41 +6,39 @@ run: issues: new: true - exclude-rules: - - linters: - - staticcheck - text: "SA1019:" - - linters: - - stylecheck - text: "ST1016:" linters: enable: + - errcheck + - gosimple + - govet + - ineffassign + - staticcheck + - typecheck + - unused + - asasalint - asciicheck - bodyclose + - decorder - depguard + - dogsled + - errname + - errorlint - gocritic - gofmt - gofumpt - goimports - - goprintffuncname - - gosimple - - govet - - ineffassign - misspell - nakedret - revive - - rowserrcheck - - staticcheck + - prealloc - stylecheck - - typecheck - unconvert - unparam - whitespace - disable: - - deadcode - - errcheck - - unused + - usestdlibvars + - wastedassign + linters-settings: goimports: diff --git a/cmd/generate/generate.go b/cmd/generate/generate.go index 9d2db6e..d12fdf6 100644 --- a/cmd/generate/generate.go +++ b/cmd/generate/generate.go @@ -27,7 +27,7 @@ func main() { OutPath: "./dal", ModelPkgPath: "./model/entity", /* Mode: gen.WithoutContext,*/ - //if you want the nullable field generation property to be pointer type, set FieldNullable true + // if you want the nullable field generation property to be pointer type, set FieldNullable true FieldNullable: true, FieldWithIndexTag: true, FieldWithTypeTag: true, diff --git a/config/config.go b/config/config.go index a27aca3..ec6ace9 100644 --- a/config/config.go +++ b/config/config.go @@ -97,7 +97,7 @@ func initDirectory(conf *Config) { err := mkdirFunc(conf.Sonic.LogDir, nil) err = mkdirFunc(conf.Sonic.UploadDir, err) if err != nil { - panic(fmt.Errorf("initDirectory err=%v", err)) + panic(fmt.Errorf("initDirectory err=%w", err)) } } diff --git a/consts/consts.go b/consts/consts.go index f480729..617433c 100644 --- a/consts/consts.go +++ b/consts/consts.go @@ -34,7 +34,7 @@ var ( ) const ( - DefaultThemeId = "caicai_anatole" + DefaultThemeID = "caicai_anatole" ThemeScreenshotsName = "screenshot" ThemeCustomSheetPrefix = "sheet_" ThemeCustomPostPrefix = "post_" diff --git a/consts/enum.go b/consts/enum.go index 2643357..d7ba800 100644 --- a/consts/enum.go +++ b/consts/enum.go @@ -229,11 +229,12 @@ func (m MFAType) MarshalJSON() ([]byte, error) { func (m *MFAType) UnmarshalJSON(data []byte) error { str := string(data) - if str == `"NONE"` { + switch str { + case `"NONE"`: *m = MFANone - } else if str == `"TFA_TOTP"` { + case `"TFA_TOTP"`: *m = MFATFATotp - } else { + default: return xerr.BadParam.New("").WithMsg("unknown MFAType") } return nil @@ -270,13 +271,14 @@ const ( ) func (c PostStatus) MarshalJSON() ([]byte, error) { - if c == PostStatusPublished { + switch c { + case PostStatusPublished: return []byte(`"PUBLISHED"`), nil - } else if c == PostStatusDraft { + case PostStatusDraft: return []byte(`"DRAFT"`), nil - } else if c == PostStatusRecycle { + case PostStatusRecycle: return []byte(`"RECYCLE"`), nil - } else if c == PostStatusIntimate { + case PostStatusIntimate: return []byte(`"INTIMATE"`), nil } return nil, nil @@ -284,17 +286,18 @@ func (c PostStatus) MarshalJSON() ([]byte, error) { func (c *PostStatus) UnmarshalJSON(data []byte) error { str := string(data) - if str == `"PUBLISHED"` { + switch str { + case `"PUBLISHED"`: *c = PostStatusPublished - } else if str == `"DRAFT"` { + case `"DRAFT"`: *c = PostStatusDraft - } else if str == `"RECYCLE"` { + case `"RECYCLE"`: *c = PostStatusRecycle - } else if str == `"INTIMATE"` { + case `"INTIMATE"`: *c = PostStatusIntimate - } else if str == "" { + case "": *c = PostStatusDraft - } else { + default: return xerr.BadParam.New("").WithMsg("unknown PostStatus") } return nil @@ -326,16 +329,18 @@ func (c PostStatus) Ptr() *PostStatus { } func PostStatusFromString(str string) (PostStatus, error) { - if str == "PUBLISHED" { + switch str { + case "PUBLISHED": return PostStatusPublished, nil - } else if str == "DRAFT" { + case "DRAFT": return PostStatusDraft, nil - } else if str == "RECYCLE" { + case "RECYCLE": return PostStatusRecycle, nil - } else if str == "INTIMATE" { + case "INTIMATE": return PostStatusIntimate, nil + default: + return PostStatusDraft, xerr.BadParam.New("").WithMsg("unknown PostStatus") } - return PostStatusDraft, xerr.BadParam.New("").WithMsg("unknown PostStatus") } type CommentStatus int32 @@ -347,11 +352,12 @@ const ( ) func (c CommentStatus) MarshalJSON() ([]byte, error) { - if c == CommentStatusPublished { + switch c { + case CommentStatusPublished: return []byte(`"PUBLISHED"`), nil - } else if c == CommentStatusAuditing { + case CommentStatusAuditing: return []byte(`"AUDITING"`), nil - } else if c == CommentStatusRecycle { + case CommentStatusRecycle: return []byte(`"RECYCLE"`), nil } return nil, nil @@ -359,13 +365,15 @@ func (c CommentStatus) MarshalJSON() ([]byte, error) { func (c *CommentStatus) UnmarshalJSON(data []byte) error { str := string(data) - if str == `"PUBLISHED"` { + + switch str { + case `"PUBLISHED"`: *c = CommentStatusPublished - } else if str == `"AUDITING"` { + case `"AUDITING"`: *c = CommentStatusAuditing - } else if str == `"RECYCLE"` { + case `"RECYCLE"`: *c = CommentStatusRecycle - } else { + default: return xerr.BadParam.New("").WithMsg("unknown CommentStatus") } return nil @@ -389,13 +397,14 @@ func (c *CommentStatus) Scan(src interface{}) error { } func CommentStatusFromString(str string) (CommentStatus, error) { - if str == "PUBLISHED" { + switch str { + case "PUBLISHED": return CommentStatusPublished, nil - } else if str == "AUDITING" { + case "AUDITING": return CommentStatusAuditing, nil - } else if str == "RECYCLE" { + case "RECYCLE": return CommentStatusRecycle, nil - } else { + default: return CommentStatusPublished, xerr.BadParam.New("").WithMsg("unknown CommentStatus") } } @@ -462,13 +471,14 @@ func (e EditorType) MarshalJSON() ([]byte, error) { func (e *EditorType) UnmarshalJSON(data []byte) error { str := string(data) - if str == `"MARKDOWN"` { + switch str { + case `"MARKDOWN"`: *e = EditorTypeMarkdown - } else if str == `"RICHTEXT"` { + case `"RICHTEXT"`: *e = EditorTypeRichText - } else if str == "" { + case "": *e = EditorTypeMarkdown - } else { + default: return xerr.BadParam.New("").WithMsg("unknown editorType") } return nil @@ -491,12 +501,12 @@ func (o OptionType) MarshalJSON() ([]byte, error) { } func (o *OptionType) UnmarshalJSON(data []byte) error { - str := string(data) - if str == `"INTERNAL"` { + switch string(data) { + case `"INTERNAL"`: *o = OptionTypeInternal - } else if str == `"CUSTOM"` { + case `"CUSTOM"`: *o = OptionTypeCustom - } else { + default: return xerr.BadParam.New("").WithMsg("unknown OptionType") } return nil @@ -608,12 +618,12 @@ func (j JournalType) MarshalJSON() ([]byte, error) { } func (j *JournalType) UnmarshalJSON(data []byte) error { - str := string(data) - if str == `"PUBLIC"` { + switch string(data) { + case `"PUBLIC"`: *j = JournalTypePublic - } else if str == `"INTIMATE"` { + case `"INTIMATE"`: *j = JournalTypeIntimate - } else { + default: return xerr.BadParam.New("").WithMsg("unknown JournalType") } return nil @@ -858,7 +868,7 @@ func (t ThemeConfigDataType) FormatToStr(value interface{}) (string, error) { case float32: valueStr = strconv.FormatFloat(float64(data), 'f', 5, 32) case float64: - valueStr = strconv.FormatFloat(float64(data), 'f', 5, 64) + valueStr = strconv.FormatFloat(data, 'f', 5, 64) default: return "", xerr.WithErrMsgf(nil, "value invalid ThemeConfigDataType") } @@ -971,12 +981,12 @@ func (c CategoryType) MarshalJSON() ([]byte, error) { } func (c *CategoryType) UnmarshalJSON(data []byte) error { - str := string(data) - if str == `"NORMAL"` { + switch string(data) { + case `"NORMAL"`: *c = CategoryTypeNormal - } else if str == `"INTIMATE"` { + case `"INTIMATE"`: *c = CategoryTypeIntimate - } else { + default: return xerr.BadParam.New("").WithMsg("unknown PostStatus") } return nil diff --git a/dal/dal.go b/dal/dal.go index 9c128c5..ec0b01e 100644 --- a/dal/dal.go +++ b/dal/dal.go @@ -28,6 +28,8 @@ var ( func NewGormDB(conf *config.Config, gormLogger logger.Interface) *gorm.DB { var err error + + //nolint:gocritic if conf.SQLite3 != nil && conf.SQLite3.Enable { DB, err = initSQLite(conf, gormLogger) if err != nil { diff --git a/event/events.go b/event/events.go index ef782fb..f6dfcee 100644 --- a/event/events.go +++ b/event/events.go @@ -26,7 +26,7 @@ type LogEvent struct { LogKey string LogType consts.LogType Content string - IpAddress string + IPAddress string } func (*LogEvent) EventType() string { diff --git a/event/listener/log.go b/event/listener/log.go index e97d7a5..8eb8d7d 100644 --- a/event/listener/log.go +++ b/event/listener/log.go @@ -29,7 +29,7 @@ func (l *LogEventListener) HandleEvent(ctx context.Context, logEvent event.Event logDAL := dal.GetQueryByCtx(ctx).Log logEntity := &entity.Log{ Content: log.Content, - IPAddress: log.IpAddress, + IPAddress: log.IPAddress, LogKey: log.LogKey, Type: log.LogType, } diff --git a/event/listener/template_config.go b/event/listener/template_config.go index 6a7a4c0..e0aaf7e 100644 --- a/event/listener/template_config.go +++ b/event/listener/template_config.go @@ -163,7 +163,7 @@ func (t *TemplateConfigListener) loadOption(ctx context.Context) error { for _, option := range options { optionMap[option.Key] = option.Value } - blogBaseURL := t.OptionService.GetOrByDefault(ctx, property.BlogUrl) + blogBaseURL := t.OptionService.GetOrByDefault(ctx, property.BlogURL) blogTitle := t.OptionService.GetOrByDefault(ctx, property.BlogTitle) blogLogo := t.OptionService.GetOrByDefault(ctx, property.BlogLogo) globalAbsolutePathEnabled := t.OptionService.GetOrByDefault(ctx, property.GlobalAbsolutePathEnabled) diff --git a/handler/admin/admin.go b/handler/admin/admin.go index 573d1d6..69a751e 100644 --- a/handler/admin/admin.go +++ b/handler/admin/admin.go @@ -1,6 +1,8 @@ package admin import ( + "errors" + "github.com/gin-gonic/gin" "github.com/go-playground/validator/v10" @@ -35,7 +37,8 @@ func (a *AdminHandler) AuthPreCheck(ctx *gin.Context) (interface{}, error) { var loginParam param.LoginParam err := ctx.ShouldBindJSON(&loginParam) if err != nil { - if e, ok := err.(validator.ValidationErrors); ok { + e := validator.ValidationErrors{} + if errors.As(err, &e) { return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e)) } return nil, xerr.BadParam.Wrapf(err, "") @@ -52,7 +55,8 @@ func (a *AdminHandler) Auth(ctx *gin.Context) (interface{}, error) { var loginParam param.LoginParam err := ctx.ShouldBindJSON(&loginParam) if err != nil { - if e, ok := err.(validator.ValidationErrors); ok { + e := validator.ValidationErrors{} + if errors.As(err, &e) { return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e)) } return nil, xerr.BadParam.Wrapf(err, "").WithStatus(xerr.StatusBadRequest) @@ -70,7 +74,8 @@ func (a *AdminHandler) SendResetCode(ctx *gin.Context) (interface{}, error) { var resetPasswordParam param.ResetPasswordParam err := ctx.ShouldBindJSON(&resetPasswordParam) if err != nil { - if e, ok := err.(validator.ValidationErrors); ok { + e := validator.ValidationErrors{} + if errors.As(err, &e) { return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e)) } return nil, xerr.BadParam.Wrapf(err, "").WithStatus(xerr.StatusBadRequest) diff --git a/handler/admin/backup.go b/handler/admin/backup.go index e366083..6f467d6 100644 --- a/handler/admin/backup.go +++ b/handler/admin/backup.go @@ -1,6 +1,7 @@ package admin import ( + "errors" "net/http" "path" "path/filepath" @@ -41,7 +42,7 @@ func (b *BackupHandler) GetDataBackup(ctx *gin.Context) (interface{}, error) { if err != nil { return nil, err } - return b.BackupService.GetBackup(ctx, filepath.Join(config.DataExportDir, filename), service.JsonData) + return b.BackupService.GetBackup(ctx, filepath.Join(config.DataExportDir, filename), service.JSONData) } func (b *BackupHandler) GetMarkDownBackup(ctx *gin.Context) (interface{}, error) { @@ -56,7 +57,8 @@ func (b *BackupHandler) BackupWholeSite(ctx *gin.Context) (interface{}, error) { toBackupItems := make([]string, 0) err := ctx.ShouldBindJSON(&toBackupItems) if err != nil { - if e, ok := err.(validator.ValidationErrors); ok { + e := validator.ValidationErrors{} + if errors.As(err, &e) { return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e)) } return nil, xerr.WithStatus(err, xerr.StatusBadRequest) @@ -98,7 +100,7 @@ func (b *BackupHandler) DownloadBackups(ctx *gin.Context) { filePath, err := b.BackupService.GetBackupFilePath(ctx, config.BackupDir, filename) if err != nil { log.CtxErrorf(ctx, "err=%+v", err) - status := xerr.GetHttpStatus(err) + status := xerr.GetHTTPStatus(err) ctx.JSON(status, &dto.BaseDTO{Status: status, Message: xerr.GetMessage(err)}) } ctx.File(filePath) @@ -142,7 +144,7 @@ func (b *BackupHandler) HandleData(ctx *gin.Context) { } func (b *BackupHandler) ListExportData(ctx *gin.Context) (interface{}, error) { - return b.BackupService.ListFiles(ctx, config.DataExportDir, service.JsonData) + return b.BackupService.ListFiles(ctx, config.DataExportDir, service.JSONData) } func (b *BackupHandler) DownloadData(ctx *gin.Context) { @@ -156,7 +158,7 @@ func (b *BackupHandler) DownloadData(ctx *gin.Context) { filePath, err := b.BackupService.GetBackupFilePath(ctx, config.DataExportDir, filename) if err != nil { log.CtxErrorf(ctx, "err=%+v", err) - status := xerr.GetHttpStatus(err) + status := xerr.GetHTTPStatus(err) ctx.JSON(status, &dto.BaseDTO{Status: status, Message: xerr.GetMessage(err)}) } ctx.File(filePath) @@ -174,7 +176,8 @@ func (b *BackupHandler) ExportMarkdown(ctx *gin.Context) (interface{}, error) { var exportMarkdownParam param.ExportMarkdown err := ctx.ShouldBindJSON(&exportMarkdownParam) if err != nil { - if e, ok := err.(validator.ValidationErrors); ok { + e := validator.ValidationErrors{} + if errors.As(err, &e) { return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e)) } return nil, xerr.WithStatus(err, xerr.StatusBadRequest) @@ -206,7 +209,7 @@ func (b *BackupHandler) DownloadMarkdown(ctx *gin.Context) { filePath, err := b.BackupService.GetBackupFilePath(ctx, config.BackupMarkdownDir, filename) if err != nil { log.CtxErrorf(ctx, "err=%+v", err) - status := xerr.GetHttpStatus(err) + status := xerr.GetHTTPStatus(err) ctx.JSON(status, &dto.BaseDTO{Status: status, Message: xerr.GetMessage(err)}) } ctx.File(filePath) @@ -219,7 +222,7 @@ func wrapHandler(handler wrapperHandler) gin.HandlerFunc { data, err := handler(ctx) if err != nil { log.CtxErrorf(ctx, "err=%+v", err) - status := xerr.GetHttpStatus(err) + status := xerr.GetHTTPStatus(err) ctx.JSON(status, &dto.BaseDTO{Status: status, Message: xerr.GetMessage(err)}) return } diff --git a/handler/admin/category.go b/handler/admin/category.go index 61245b0..1239553 100644 --- a/handler/admin/category.go +++ b/handler/admin/category.go @@ -1,6 +1,8 @@ package admin import ( + "errors" + "github.com/gin-gonic/gin" "github.com/go-playground/validator/v10" @@ -26,7 +28,7 @@ func (c *CategoryHandler) GetCategoryByID(ctx *gin.Context) (interface{}, error) if err != nil { return nil, err } - category, err := c.CategoryService.GetByID(ctx, int32(id)) + category, err := c.CategoryService.GetByID(ctx, id) if err != nil { return nil, err } @@ -72,7 +74,8 @@ func (c *CategoryHandler) CreateCategory(ctx *gin.Context) (interface{}, error) var categoryParam param.Category err := ctx.ShouldBindJSON(&categoryParam) if err != nil { - if e, ok := err.(validator.ValidationErrors); ok { + e := validator.ValidationErrors{} + if errors.As(err, &e) { return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e)) } return nil, xerr.WithStatus(err, xerr.StatusBadRequest) @@ -88,7 +91,8 @@ func (c *CategoryHandler) UpdateCategory(ctx *gin.Context) (interface{}, error) var categoryParam param.Category err := ctx.ShouldBindJSON(&categoryParam) if err != nil { - if e, ok := err.(validator.ValidationErrors); ok { + e := validator.ValidationErrors{} + if errors.As(err, &e) { return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e)) } return nil, xerr.WithStatus(err, xerr.StatusBadRequest) @@ -109,7 +113,8 @@ func (c *CategoryHandler) UpdateCategoryBatch(ctx *gin.Context) (interface{}, er categoryParams := make([]*param.Category, 0) err := ctx.ShouldBindJSON(&categoryParams) if err != nil { - if e, ok := err.(validator.ValidationErrors); ok { + e := validator.ValidationErrors{} + if errors.As(err, &e) { return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e)) } return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error") diff --git a/handler/admin/comment_journal.go b/handler/admin/comment_journal.go index 3e8525a..563419f 100644 --- a/handler/admin/comment_journal.go +++ b/handler/admin/comment_journal.go @@ -1,6 +1,8 @@ package admin import ( + "errors" + "github.com/gin-gonic/gin" "github.com/go-playground/validator/v10" @@ -133,7 +135,8 @@ func (j *JournalCommentHandler) CreateJournalComment(ctx *gin.Context) (interfac var commentParam *param.AdminComment err := ctx.ShouldBindJSON(&commentParam) if err != nil { - if e, ok := err.(validator.ValidationErrors); ok { + e := validator.ValidationErrors{} + if errors.As(err, &e) { return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e)) } return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error") @@ -187,7 +190,8 @@ func (j *JournalCommentHandler) UpdateJournalComment(ctx *gin.Context) (interfac var commentParam *param.Comment err = ctx.ShouldBindJSON(&commentParam) if err != nil { - if e, ok := err.(validator.ValidationErrors); ok { + e := validator.ValidationErrors{} + if errors.As(err, &e) { return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e)) } return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error") diff --git a/handler/admin/comment_post.go b/handler/admin/comment_post.go index 3e65734..bf52349 100644 --- a/handler/admin/comment_post.go +++ b/handler/admin/comment_post.go @@ -1,6 +1,8 @@ package admin import ( + "errors" + "github.com/gin-gonic/gin" "github.com/go-playground/validator/v10" @@ -139,7 +141,8 @@ func (p *PostCommentHandler) CreatePostComment(ctx *gin.Context) (interface{}, e var commentParam *param.AdminComment err := ctx.ShouldBindJSON(&commentParam) if err != nil { - if e, ok := err.(validator.ValidationErrors); ok { + e := validator.ValidationErrors{} + if errors.As(err, &e) { return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e)) } return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error") @@ -177,7 +180,8 @@ func (p *PostCommentHandler) UpdatePostComment(ctx *gin.Context) (interface{}, e var commentParam *param.Comment err = ctx.ShouldBindJSON(&commentParam) if err != nil { - if e, ok := err.(validator.ValidationErrors); ok { + e := validator.ValidationErrors{} + if errors.As(err, &e) { return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e)) } return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error") diff --git a/handler/admin/comment_sheet.go b/handler/admin/comment_sheet.go index 3ad33c1..4784f18 100644 --- a/handler/admin/comment_sheet.go +++ b/handler/admin/comment_sheet.go @@ -2,6 +2,7 @@ package admin import ( "context" + "errors" "github.com/gin-gonic/gin" "github.com/go-playground/validator/v10" @@ -146,7 +147,8 @@ func (s *SheetCommentHandler) CreateSheetComment(ctx *gin.Context) (interface{}, var commentParam *param.AdminComment err := ctx.ShouldBindJSON(&commentParam) if err != nil { - if e, ok := err.(validator.ValidationErrors); ok { + e := validator.ValidationErrors{} + if errors.As(err, &e) { return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e)) } return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error") diff --git a/handler/admin/install.go b/handler/admin/install.go index db18a64..0770efb 100644 --- a/handler/admin/install.go +++ b/handler/admin/install.go @@ -1,6 +1,8 @@ package admin import ( + "errors" + "github.com/gin-gonic/gin" "github.com/go-playground/validator/v10" @@ -24,7 +26,8 @@ func (i *InstallHandler) InstallBlog(ctx *gin.Context) (interface{}, error) { var installParam param.Install err := ctx.ShouldBindJSON(&installParam) if err != nil { - if e, ok := err.(validator.ValidationErrors); ok { + e := validator.ValidationErrors{} + if errors.As(err, &e) { return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e)) } return nil, xerr.WithStatus(err, xerr.StatusBadRequest) diff --git a/handler/admin/journal.go b/handler/admin/journal.go index 3e3b816..989fa79 100644 --- a/handler/admin/journal.go +++ b/handler/admin/journal.go @@ -1,6 +1,8 @@ package admin import ( + "errors" + "github.com/gin-gonic/gin" "github.com/go-playground/validator/v10" @@ -63,7 +65,8 @@ func (j *JournalHandler) CreateJournal(ctx *gin.Context) (interface{}, error) { var journalParam param.Journal err := ctx.ShouldBindJSON(&journalParam) if err != nil { - if e, ok := err.(validator.ValidationErrors); ok { + e := validator.ValidationErrors{} + if errors.As(err, &e) { return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e)) } return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error") @@ -82,7 +85,8 @@ func (j *JournalHandler) UpdateJournal(ctx *gin.Context) (interface{}, error) { var journalParam param.Journal err := ctx.ShouldBindJSON(&journalParam) if err != nil { - if e, ok := err.(validator.ValidationErrors); ok { + e := validator.ValidationErrors{} + if errors.As(err, &e) { return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e)) } return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error") @@ -100,5 +104,5 @@ func (j *JournalHandler) DeleteJournal(ctx *gin.Context) (interface{}, error) { if err != nil { return nil, err } - return nil, j.JournalService.Delete(ctx, int32(journalID)) + return nil, j.JournalService.Delete(ctx, journalID) } diff --git a/handler/admin/link.go b/handler/admin/link.go index c0c4cbf..d3e4518 100644 --- a/handler/admin/link.go +++ b/handler/admin/link.go @@ -1,6 +1,8 @@ package admin import ( + "errors" + "github.com/gin-gonic/gin" "github.com/go-playground/validator/v10" @@ -56,7 +58,8 @@ func (l *LinkHandler) CreateLink(ctx *gin.Context) (interface{}, error) { linkParam := ¶m.Link{} err := ctx.ShouldBindJSON(linkParam) if err != nil { - if e, ok := err.(validator.ValidationErrors); ok { + e := validator.ValidationErrors{} + if errors.As(err, &e) { return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e)) } return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error") @@ -77,7 +80,8 @@ func (l *LinkHandler) UpdateLink(ctx *gin.Context) (interface{}, error) { err = ctx.ShouldBindJSON(linkParam) if err != nil { - if e, ok := err.(validator.ValidationErrors); ok { + e := validator.ValidationErrors{} + if errors.As(err, &e) { return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e)) } return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error") diff --git a/handler/admin/menu.go b/handler/admin/menu.go index e473f3b..bbeeffe 100644 --- a/handler/admin/menu.go +++ b/handler/admin/menu.go @@ -1,6 +1,8 @@ package admin import ( + "errors" + "github.com/gin-gonic/gin" "github.com/go-playground/validator/v10" @@ -97,7 +99,8 @@ func (m *MenuHandler) CreateMenu(ctx *gin.Context) (interface{}, error) { menuParam := ¶m.Menu{} err := ctx.ShouldBindJSON(menuParam) if err != nil { - if e, ok := err.(validator.ValidationErrors); ok { + e := validator.ValidationErrors{} + if errors.As(err, &e) { return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e)) } return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error") @@ -113,7 +116,8 @@ func (m *MenuHandler) CreateMenuBatch(ctx *gin.Context) (interface{}, error) { menuParams := make([]*param.Menu, 0) err := ctx.ShouldBindJSON(&menuParams) if err != nil { - if e, ok := err.(validator.ValidationErrors); ok { + e := validator.ValidationErrors{} + if errors.As(err, &e) { return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e)) } return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error") @@ -134,7 +138,8 @@ func (m *MenuHandler) UpdateMenu(ctx *gin.Context) (interface{}, error) { err = ctx.ShouldBindJSON(menuParam) if err != nil { - if e, ok := err.(validator.ValidationErrors); ok { + e := validator.ValidationErrors{} + if errors.As(err, &e) { return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e)) } return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error") @@ -150,7 +155,8 @@ func (m *MenuHandler) UpdateMenuBatch(ctx *gin.Context) (interface{}, error) { menuParams := make([]*param.Menu, 0) err := ctx.ShouldBindJSON(&menuParams) if err != nil { - if e, ok := err.(validator.ValidationErrors); ok { + e := validator.ValidationErrors{} + if errors.As(err, &e) { return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e)) } return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error") diff --git a/handler/admin/photo.go b/handler/admin/photo.go index e1a663b..e213ce6 100644 --- a/handler/admin/photo.go +++ b/handler/admin/photo.go @@ -1,6 +1,8 @@ package admin import ( + "errors" + "github.com/gin-gonic/gin" "github.com/go-playground/validator/v10" @@ -74,7 +76,8 @@ func (p *PhotoHandler) CreatePhoto(ctx *gin.Context) (interface{}, error) { photoParam := ¶m.Photo{} err := ctx.ShouldBindJSON(photoParam) if err != nil { - if e, ok := err.(validator.ValidationErrors); ok { + e := validator.ValidationErrors{} + if errors.As(err, &e) { return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e)) } return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error") @@ -95,7 +98,8 @@ func (p *PhotoHandler) UpdatePhoto(ctx *gin.Context) (interface{}, error) { err = ctx.ShouldBindJSON(photoParam) if err != nil { - if e, ok := err.(validator.ValidationErrors); ok { + e := validator.ValidationErrors{} + if errors.As(err, &e) { return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e)) } return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error") diff --git a/handler/admin/post.go b/handler/admin/post.go index adc005d..35a13a9 100644 --- a/handler/admin/post.go +++ b/handler/admin/post.go @@ -1,6 +1,7 @@ package admin import ( + "errors" "strconv" "github.com/gin-gonic/gin" @@ -154,14 +155,15 @@ func (p *PostHandler) LikePost(ctx *gin.Context) (interface{}, error) { if err != nil { return nil, err } - return nil, p.PostService.IncreaseLike(ctx, int32(postID)) + return nil, p.PostService.IncreaseLike(ctx, postID) } func (p *PostHandler) CreatePost(ctx *gin.Context) (interface{}, error) { var postParam param.Post err := ctx.ShouldBindJSON(&postParam) if err != nil { - if e, ok := err.(validator.ValidationErrors); ok { + e := validator.ValidationErrors{} + if errors.As(err, &e) { return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e)) } return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error") @@ -178,7 +180,8 @@ func (p *PostHandler) UpdatePost(ctx *gin.Context) (interface{}, error) { var postParam param.Post err := ctx.ShouldBindJSON(&postParam) if err != nil { - if e, ok := err.(validator.ValidationErrors); ok { + e := validator.ValidationErrors{} + if errors.As(err, &e) { return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e)) } return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error") @@ -214,7 +217,7 @@ func (p *PostHandler) UpdatePostStatus(ctx *gin.Context) (interface{}, error) { if int32(status) < int32(consts.PostStatusPublished) || int32(status) > int32(consts.PostStatusIntimate) { return nil, xerr.WithStatus(nil, xerr.StatusBadRequest).WithMsg("status error") } - post, err := p.PostService.UpdateStatus(ctx, int32(postID), consts.PostStatus(status)) + post, err := p.PostService.UpdateStatus(ctx, int32(postID), status) if err != nil { return nil, err } @@ -239,7 +242,7 @@ func (p *PostHandler) UpdatePostStatusBatch(ctx *gin.Context) (interface{}, erro return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("post ids error") } - return p.PostService.UpdateStatusBatch(ctx, consts.PostStatus(status), ids) + return p.PostService.UpdateStatusBatch(ctx, status, ids) } func (p *PostHandler) UpdatePostDraft(ctx *gin.Context) (interface{}, error) { @@ -252,7 +255,7 @@ func (p *PostHandler) UpdatePostDraft(ctx *gin.Context) (interface{}, error) { if err != nil { return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("content param error") } - post, err := p.PostService.UpdateDraftContent(ctx, int32(postID), postContentParam.Content) + post, err := p.PostService.UpdateDraftContent(ctx, postID, postContentParam.Content) if err != nil { return nil, err } @@ -281,5 +284,5 @@ func (p *PostHandler) PreviewPost(ctx *gin.Context) (interface{}, error) { if err != nil { return nil, err } - return p.PostService.Preview(ctx, int32(postID)) + return p.PostService.Preview(ctx, postID) } diff --git a/handler/admin/sheet.go b/handler/admin/sheet.go index 6a3fe58..a9c9832 100644 --- a/handler/admin/sheet.go +++ b/handler/admin/sheet.go @@ -1,6 +1,8 @@ package admin import ( + "errors" + "github.com/gin-gonic/gin" "github.com/go-playground/validator/v10" @@ -69,7 +71,8 @@ func (s *SheetHandler) CreateSheet(ctx *gin.Context) (interface{}, error) { var sheetParam param.Sheet err := ctx.ShouldBindJSON(&sheetParam) if err != nil { - if e, ok := err.(validator.ValidationErrors); ok { + e := validator.ValidationErrors{} + if errors.As(err, &e) { return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e)) } return nil, xerr.WithStatus(err, xerr.StatusBadRequest) @@ -89,7 +92,8 @@ func (s *SheetHandler) UpdateSheet(ctx *gin.Context) (interface{}, error) { var sheetParam param.Sheet err := ctx.ShouldBindJSON(&sheetParam) if err != nil { - if e, ok := err.(validator.ValidationErrors); ok { + e := validator.ValidationErrors{} + if errors.As(err, &e) { return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e)) } return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error") @@ -111,14 +115,18 @@ func (s *SheetHandler) UpdateSheetStatus(ctx *gin.Context) (interface{}, error) if err != nil { return nil, err } - status, err := util.ParamInt32(ctx, "status") + statusStr, err := util.ParamString(ctx, "status") + if err != nil { + return nil, err + } + status, err := consts.PostStatusFromString(statusStr) if err != nil { return nil, err } - if status < int32(consts.PostStatusPublished) || status > int32(consts.PostStatusIntimate) { + if status < consts.PostStatusPublished || status > consts.PostStatusIntimate { return nil, xerr.WithStatus(nil, xerr.StatusBadRequest).WithMsg("status error") } - return s.SheetService.UpdateStatus(ctx, sheetID, consts.PostStatus(status)) + return s.SheetService.UpdateStatus(ctx, sheetID, status) } func (s *SheetHandler) UpdateSheetDraft(ctx *gin.Context) (interface{}, error) { @@ -131,7 +139,7 @@ func (s *SheetHandler) UpdateSheetDraft(ctx *gin.Context) (interface{}, error) { if err != nil { return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("content param error") } - post, err := s.SheetService.UpdateDraftContent(ctx, int32(sheetID), postContentParam.Content) + post, err := s.SheetService.UpdateDraftContent(ctx, sheetID, postContentParam.Content) if err != nil { return nil, err } @@ -143,7 +151,7 @@ func (s *SheetHandler) DeleteSheet(ctx *gin.Context) (interface{}, error) { if err != nil { return nil, err } - return nil, s.SheetService.Delete(ctx, int32(sheetID)) + return nil, s.SheetService.Delete(ctx, sheetID) } func (s *SheetHandler) PreviewSheet(ctx *gin.Context) (interface{}, error) { @@ -151,5 +159,5 @@ func (s *SheetHandler) PreviewSheet(ctx *gin.Context) (interface{}, error) { if err != nil { return nil, err } - return s.PostService.Preview(ctx, int32(sheetID)) + return s.PostService.Preview(ctx, sheetID) } diff --git a/handler/admin/tag.go b/handler/admin/tag.go index 47408e4..29b67fe 100644 --- a/handler/admin/tag.go +++ b/handler/admin/tag.go @@ -1,6 +1,8 @@ package admin import ( + "errors" + "github.com/gin-gonic/gin" "github.com/go-playground/validator/v10" @@ -59,7 +61,8 @@ func (t *TagHandler) CreateTag(ctx *gin.Context) (interface{}, error) { tagParam := ¶m.Tag{} err := ctx.ShouldBindJSON(tagParam) if err != nil { - if e, ok := err.(validator.ValidationErrors); ok { + e := validator.ValidationErrors{} + if errors.As(err, &e) { return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e)) } return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error") @@ -80,7 +83,8 @@ func (t *TagHandler) UpdateTag(ctx *gin.Context) (interface{}, error) { err = ctx.ShouldBindJSON(tagParam) if err != nil { - if e, ok := err.(validator.ValidationErrors); ok { + e := validator.ValidationErrors{} + if errors.As(err, &e) { return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e)) } return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error") diff --git a/handler/admin/theme.go b/handler/admin/theme.go index 50e2fb2..4b29d01 100644 --- a/handler/admin/theme.go +++ b/handler/admin/theme.go @@ -1,6 +1,8 @@ package admin import ( + "errors" + "github.com/gin-gonic/gin" "github.com/go-playground/validator/v10" @@ -37,7 +39,7 @@ func (t *ThemeHandler) ListAllThemes(ctx *gin.Context) (interface{}, error) { } func (t *ThemeHandler) ListActivatedThemeFile(ctx *gin.Context) (interface{}, error) { - activatedThemeID, err := t.OptionService.GetActivatedThemeId(ctx) + activatedThemeID, err := t.OptionService.GetActivatedThemeID(ctx) if err != nil { return nil, err } @@ -57,7 +59,7 @@ func (t *ThemeHandler) GetThemeFileContent(ctx *gin.Context) (interface{}, error if err != nil { return nil, err } - activatedThemeID, err := t.OptionService.GetActivatedThemeId(ctx) + activatedThemeID, err := t.OptionService.GetActivatedThemeID(ctx) if err != nil { return nil, err } @@ -82,13 +84,14 @@ func (t *ThemeHandler) UpdateThemeFile(ctx *gin.Context) (interface{}, error) { err := ctx.ShouldBindJSON(themeParam) if err != nil { if err != nil { - if e, ok := err.(validator.ValidationErrors); ok { + e := validator.ValidationErrors{} + if errors.As(err, &e) { return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e)) } return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error") } } - activatedThemeID, err := t.OptionService.GetActivatedThemeId(ctx) + activatedThemeID, err := t.OptionService.GetActivatedThemeID(ctx) if err != nil { return nil, err } @@ -104,7 +107,8 @@ func (t *ThemeHandler) UpdateThemeFileByID(ctx *gin.Context) (interface{}, error err = ctx.ShouldBindJSON(themeParam) if err != nil { if err != nil { - if e, ok := err.(validator.ValidationErrors); ok { + e := validator.ValidationErrors{} + if errors.As(err, &e) { return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e)) } return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error") @@ -114,7 +118,7 @@ func (t *ThemeHandler) UpdateThemeFileByID(ctx *gin.Context) (interface{}, error } func (t *ThemeHandler) ListCustomSheetTemplate(ctx *gin.Context) (interface{}, error) { - activatedThemeID, err := t.OptionService.GetActivatedThemeId(ctx) + activatedThemeID, err := t.OptionService.GetActivatedThemeID(ctx) if err != nil { return nil, err } @@ -122,7 +126,7 @@ func (t *ThemeHandler) ListCustomSheetTemplate(ctx *gin.Context) (interface{}, e } func (t *ThemeHandler) ListCustomPostTemplate(ctx *gin.Context) (interface{}, error) { - activatedThemeID, err := t.OptionService.GetActivatedThemeId(ctx) + activatedThemeID, err := t.OptionService.GetActivatedThemeID(ctx) if err != nil { return nil, err } @@ -138,7 +142,7 @@ func (t *ThemeHandler) ActivateTheme(ctx *gin.Context) (interface{}, error) { } func (t *ThemeHandler) GetActivatedTheme(ctx *gin.Context) (interface{}, error) { - activatedThemeID, err := t.OptionService.GetActivatedThemeId(ctx) + activatedThemeID, err := t.OptionService.GetActivatedThemeID(ctx) if err != nil { return nil, err } @@ -146,7 +150,7 @@ func (t *ThemeHandler) GetActivatedTheme(ctx *gin.Context) (interface{}, error) } func (t *ThemeHandler) GetActivatedThemeConfig(ctx *gin.Context) (interface{}, error) { - activatedThemeID, err := t.OptionService.GetActivatedThemeId(ctx) + activatedThemeID, err := t.OptionService.GetActivatedThemeID(ctx) if err != nil { return nil, err } @@ -199,7 +203,7 @@ func (t *ThemeHandler) GetThemeConfigGroupNames(ctx *gin.Context) (interface{}, } func (t *ThemeHandler) GetActivatedThemeSettingMap(ctx *gin.Context) (interface{}, error) { - activatedThemeID, err := t.OptionService.GetActivatedThemeId(ctx) + activatedThemeID, err := t.OptionService.GetActivatedThemeID(ctx) if err != nil { return nil, err } @@ -227,7 +231,7 @@ func (t *ThemeHandler) GetThemeSettingMapByGroupAndThemeID(ctx *gin.Context) (in } func (t *ThemeHandler) SaveActivatedThemeSetting(ctx *gin.Context) (interface{}, error) { - activatedThemeID, err := t.OptionService.GetActivatedThemeId(ctx) + activatedThemeID, err := t.OptionService.GetActivatedThemeID(ctx) if err != nil { return nil, err } diff --git a/handler/admin/user.go b/handler/admin/user.go index 1c602b7..92817de 100644 --- a/handler/admin/user.go +++ b/handler/admin/user.go @@ -1,6 +1,8 @@ package admin import ( + "errors" + "github.com/gin-gonic/gin" "github.com/go-playground/validator/v10" @@ -37,7 +39,8 @@ func (u *UserHandler) UpdateUserProfile(ctx *gin.Context) (interface{}, error) { userParam := ¶m.User{} err := ctx.ShouldBindJSON(userParam) if err != nil { - if e, ok := err.(validator.ValidationErrors); ok { + e := validator.ValidationErrors{} + if errors.As(err, &e) { return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e)) } return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error") @@ -57,7 +60,8 @@ func (u *UserHandler) UpdatePassword(ctx *gin.Context) (interface{}, error) { passwordParam := &Password{} err := ctx.ShouldBindJSON(passwordParam) if err != nil { - if e, ok := err.(validator.ValidationErrors); ok { + e := validator.ValidationErrors{} + if errors.As(err, &e) { return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e)) } return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error") @@ -72,7 +76,8 @@ func (u *UserHandler) GenerateMFAQRCode(ctx *gin.Context) (interface{}, error) { param := &Param{} err := ctx.ShouldBindJSON(param) if err != nil { - if e, ok := err.(validator.ValidationErrors); ok { + e := validator.ValidationErrors{} + if errors.As(err, &e) { return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e)) } return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error") @@ -92,7 +97,7 @@ func (u *UserHandler) GenerateMFAQRCode(ctx *gin.Context) (interface{}, error) { return nil, err } mfaFactorAuthDTO.MFAType = consts.MFATFATotp - mfaFactorAuthDTO.OptAuthUrl = url + mfaFactorAuthDTO.OptAuthURL = url mfaFactorAuthDTO.MFAKey = key qrCode, err := u.TwoFactorMFAService.GenerateMFAQRCode(ctx, url) if err != nil { @@ -114,7 +119,8 @@ func (u *UserHandler) UpdateMFA(ctx *gin.Context) (interface{}, error) { mfaParam := &Param{} err := ctx.ShouldBindJSON(mfaParam) if err != nil { - if e, ok := err.(validator.ValidationErrors); ok { + e := validator.ValidationErrors{} + if errors.As(err, &e) { return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e)) } return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error") diff --git a/handler/binding/form_binding.go b/handler/binding/form_binding.go index 3e68d2c..09e4654 100644 --- a/handler/binding/form_binding.go +++ b/handler/binding/form_binding.go @@ -1,6 +1,7 @@ package binding import ( + "errors" "net/http" "github.com/gin-gonic/gin/binding" @@ -10,8 +11,10 @@ const defaultMemory = 32 << 20 // CustomFormBinding If the type implements the UnmarshalJSON interface, use JSON to bind // For the purpose of support enum string to turn the enum type binding -var CustomFormBinding = customFormBinding{} -var CustomFormPostBinding = customFormPostBinding{} +var ( + CustomFormBinding = customFormBinding{} + CustomFormPostBinding = customFormPostBinding{} +) type ( customFormBinding struct{} @@ -27,7 +30,7 @@ func (customFormBinding) Bind(req *http.Request, obj interface{}) error { return err } if err := req.ParseMultipartForm(defaultMemory); err != nil { - if err != http.ErrNotMultipart { + if !errors.Is(err, http.ErrNotMultipart) { return err } } diff --git a/handler/binding/form_mapping.go b/handler/binding/form_mapping.go index 625b292..5d10f79 100644 --- a/handler/binding/form_mapping.go +++ b/handler/binding/form_mapping.go @@ -212,8 +212,7 @@ func setWithProperType(val string, value reflect.Value, field reflect.StructFiel case reflect.Int32: return setIntField(val, 32, value) case reflect.Int64: - switch value.Interface().(type) { - case time.Duration: + if _, ok := value.Interface().(time.Duration); ok { return setTimeDuration(val, value) } return setIntField(val, 64, value) @@ -236,8 +235,7 @@ func setWithProperType(val string, value reflect.Value, field reflect.StructFiel case reflect.String: value.SetString(val) case reflect.Struct: - switch value.Interface().(type) { - case time.Time: + if _, ok := value.Interface().(time.Time); ok { return setTimeField(val, field, value) } return json.Unmarshal(util.StringToBytes(val), value.Addr().Interface()) diff --git a/handler/content/api/sheet.go b/handler/content/api/sheet.go index b1d9655..8d4bc16 100644 --- a/handler/content/api/sheet.go +++ b/handler/content/api/sheet.go @@ -37,12 +37,12 @@ func NewSheetHandler( } } -func (j *SheetHandler) ListTopComment(ctx *gin.Context) (interface{}, error) { +func (s *SheetHandler) ListTopComment(ctx *gin.Context) (interface{}, error) { sheetID, err := util.ParamInt32(ctx, "sheetID") if err != nil { return nil, err } - pageSize := j.OptionService.GetOrByDefault(ctx, property.CommentPageSize).(int) + pageSize := s.OptionService.GetOrByDefault(ctx, property.CommentPageSize).(int) commentQuery := param.CommentQuery{} err = ctx.ShouldBindWith(&commentQuery, binding.CustomFormBinding) @@ -60,19 +60,19 @@ func (j *SheetHandler) ListTopComment(ctx *gin.Context) (interface{}, error) { commentQuery.PageSize = pageSize commentQuery.ParentID = util.Int32Ptr(0) - comments, totalCount, err := j.SheetCommentService.Page(ctx, commentQuery, consts.CommentTypeSheet) + comments, totalCount, err := s.SheetCommentService.Page(ctx, commentQuery, consts.CommentTypeSheet) if err != nil { return nil, err } - _ = j.SheetCommentAssembler.ClearSensitiveField(ctx, comments) - commenVOs, err := j.SheetCommentAssembler.ConvertToWithHasChildren(ctx, comments) + _ = s.SheetCommentAssembler.ClearSensitiveField(ctx, comments) + commenVOs, err := s.SheetCommentAssembler.ConvertToWithHasChildren(ctx, comments) if err != nil { return nil, err } return dto.NewPage(commenVOs, totalCount, commentQuery.Page), nil } -func (j *SheetHandler) ListChildren(ctx *gin.Context) (interface{}, error) { +func (s *SheetHandler) ListChildren(ctx *gin.Context) (interface{}, error) { sheetID, err := util.ParamInt32(ctx, "sheetID") if err != nil { return nil, err @@ -81,20 +81,20 @@ func (j *SheetHandler) ListChildren(ctx *gin.Context) (interface{}, error) { if err != nil { return nil, err } - children, err := j.SheetCommentService.GetChildren(ctx, parentID, sheetID, consts.CommentTypeSheet) + children, err := s.SheetCommentService.GetChildren(ctx, parentID, sheetID, consts.CommentTypeSheet) if err != nil { return nil, err } - _ = j.SheetCommentAssembler.ClearSensitiveField(ctx, children) - return j.SheetCommentAssembler.ConvertToDTOList(ctx, children) + _ = s.SheetCommentAssembler.ClearSensitiveField(ctx, children) + return s.SheetCommentAssembler.ConvertToDTOList(ctx, children) } -func (p *SheetHandler) ListCommentTree(ctx *gin.Context) (interface{}, error) { +func (s *SheetHandler) ListCommentTree(ctx *gin.Context) (interface{}, error) { sheetID, err := util.ParamInt32(ctx, "sheetID") if err != nil { return nil, err } - pageSize := p.OptionService.GetOrByDefault(ctx, property.CommentPageSize).(int) + pageSize := s.OptionService.GetOrByDefault(ctx, property.CommentPageSize).(int) commentQuery := param.CommentQuery{} err = ctx.ShouldBindWith(&commentQuery, binding.CustomFormBinding) @@ -112,24 +112,24 @@ func (p *SheetHandler) ListCommentTree(ctx *gin.Context) (interface{}, error) { commentQuery.PageSize = pageSize commentQuery.ParentID = util.Int32Ptr(0) - allComments, err := p.SheetCommentService.GetByContentID(ctx, sheetID, consts.CommentTypeSheet, commentQuery.Sort) + allComments, err := s.SheetCommentService.GetByContentID(ctx, sheetID, consts.CommentTypeSheet, commentQuery.Sort) if err != nil { return nil, err } - _ = p.SheetCommentAssembler.ClearSensitiveField(ctx, allComments) - commentVOs, total, err := p.SheetCommentAssembler.PageConvertToVOs(ctx, allComments, commentQuery.Page) + _ = s.SheetCommentAssembler.ClearSensitiveField(ctx, allComments) + commentVOs, total, err := s.SheetCommentAssembler.PageConvertToVOs(ctx, allComments, commentQuery.Page) if err != nil { return nil, err } return dto.NewPage(commentVOs, total, commentQuery.Page), nil } -func (p *SheetHandler) ListComment(ctx *gin.Context) (interface{}, error) { +func (s *SheetHandler) ListComment(ctx *gin.Context) (interface{}, error) { sheetID, err := util.ParamInt32(ctx, "sheetID") if err != nil { return nil, err } - pageSize := p.OptionService.GetOrByDefault(ctx, property.CommentPageSize).(int) + pageSize := s.OptionService.GetOrByDefault(ctx, property.CommentPageSize).(int) commentQuery := param.CommentQuery{} err = ctx.ShouldBindWith(&commentQuery, binding.CustomFormBinding) @@ -147,21 +147,21 @@ func (p *SheetHandler) ListComment(ctx *gin.Context) (interface{}, error) { commentQuery.PageSize = pageSize commentQuery.ParentID = util.Int32Ptr(0) - comments, total, err := p.SheetCommentService.Page(ctx, commentQuery, consts.CommentTypeSheet) + comments, total, err := s.SheetCommentService.Page(ctx, commentQuery, consts.CommentTypeSheet) if err != nil { return nil, err } - _ = p.SheetCommentAssembler.ClearSensitiveField(ctx, comments) - result, err := p.SheetCommentAssembler.ConvertToWithParentVO(ctx, comments) + _ = s.SheetCommentAssembler.ClearSensitiveField(ctx, comments) + result, err := s.SheetCommentAssembler.ConvertToWithParentVO(ctx, comments) if err != nil { return nil, err } return dto.NewPage(result, total, commentQuery.Page), nil } -func (p *SheetHandler) CreateComment(ctx *gin.Context) (interface{}, error) { +func (s *SheetHandler) CreateComment(ctx *gin.Context) (interface{}, error) { comment := param.Comment{} - err := ctx.ShouldBindJSON(&p) + err := ctx.ShouldBindJSON(&comment) if err != nil { return nil, err } @@ -170,9 +170,9 @@ func (p *SheetHandler) CreateComment(ctx *gin.Context) (interface{}, error) { comment.Content = template.HTMLEscapeString(comment.Content) comment.Email = template.HTMLEscapeString(comment.Email) comment.CommentType = consts.CommentTypeSheet - result, err := p.SheetCommentService.CreateBy(ctx, &comment) + result, err := s.SheetCommentService.CreateBy(ctx, &comment) if err != nil { return nil, err } - return p.SheetCommentAssembler.ConvertToDTO(ctx, result) + return s.SheetCommentAssembler.ConvertToDTO(ctx, result) } diff --git a/handler/content/authentication/category_authentication.go b/handler/content/authentication/category_authentication.go index 43c5946..6e54077 100644 --- a/handler/content/authentication/category_authentication.go +++ b/handler/content/authentication/category_authentication.go @@ -54,20 +54,20 @@ func (c *CategoryAuthentication) Authenticate(ctx context.Context, token string, if !ok || parentCategory == nil { return "", nil } - if parentCategory.Password == "" { + switch parentCategory.Password { + case "": parentID = parentCategory.ParentID parentIDs = append(parentIDs, parentID) - } else if parentCategory.Password == password { + case password: return c.doAuthenticate(ctx, token, parentIDs...) - } else { + default: return "", xerr.WithMsg(nil, "密码不正确").WithStatus(http.StatusUnauthorized) } } } else if category.Password == password { return c.doAuthenticate(ctx, token, id) - } else { - return "", xerr.WithMsg(nil, "密码不正确").WithStatus(http.StatusUnauthorized) } + return "", xerr.WithMsg(nil, "密码不正确").WithStatus(http.StatusUnauthorized) } func (c *CategoryAuthentication) IsAuthenticated(ctx context.Context, tokenStr string, id int32) (bool, error) { @@ -83,7 +83,7 @@ func (c *CategoryAuthentication) IsAuthenticated(ctx context.Context, tokenStr s } token, err := jwt.ParseWithClaims(tokenStr, &customClaims{}, func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { - return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) + return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) } return []byte(secret.(string)), nil }) @@ -117,7 +117,7 @@ func (c *CategoryAuthentication) doAuthenticate(ctx context.Context, tokenStr st if tokenStr != "" { token, err := jwt.ParseWithClaims(tokenStr, &customClaims{}, func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { - return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) + return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) } return []byte(secret.(string)), nil }) diff --git a/handler/content/authentication/post_authentication.go b/handler/content/authentication/post_authentication.go index 589a8a3..8394e83 100644 --- a/handler/content/authentication/post_authentication.go +++ b/handler/content/authentication/post_authentication.go @@ -75,11 +75,12 @@ func (p *PostAuthentication) Authenticate(ctx context.Context, token string, id if !ok || parentCategory == nil { break } - if parentCategory.Password == "" { + switch parentCategory.Password { + case "": parentID = parentCategory.ParentID - } else if parentCategory.Password == password { + case password: return p.doAuthenticate(ctx, token, id) - } else { + default: break } } @@ -107,7 +108,7 @@ func (p *PostAuthentication) IsAuthenticated(ctx context.Context, tokenStr strin token, err := jwt.ParseWithClaims(tokenStr, &customClaims{}, func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { - return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) + return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) } return []byte(secret.(string)), nil }) @@ -160,7 +161,7 @@ func (p *PostAuthentication) doAuthenticate(ctx context.Context, tokenStr string if tokenStr != "" { token, err := jwt.ParseWithClaims(tokenStr, &customClaims{}, func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { - return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) + return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) } return []byte(secret.(string)), nil }) diff --git a/handler/content/model/journal.go b/handler/content/model/journal.go index d13684b..6ea7ceb 100644 --- a/handler/content/model/journal.go +++ b/handler/content/model/journal.go @@ -13,7 +13,6 @@ import ( func NewJournalModel(optionService service.OptionService, themeService service.ThemeService, journalService service.JournalService, - JournalService service.JournalService, ) *JournalModel { return &JournalModel{ OptionService: optionService, diff --git a/handler/content/model/photo.go b/handler/content/model/photo.go index 45faabc..addff3c 100644 --- a/handler/content/model/photo.go +++ b/handler/content/model/photo.go @@ -13,7 +13,6 @@ import ( func NewPhotoModel(optionService service.OptionService, themeService service.ThemeService, photoService service.PhotoService, - PhotoService service.PhotoService, ) *PhotoModel { return &PhotoModel{ OptionService: optionService, diff --git a/handler/content/model/post.go b/handler/content/model/post.go index 8c6a6c7..8c77a1c 100644 --- a/handler/content/model/post.go +++ b/handler/content/model/post.go @@ -126,13 +126,13 @@ func (p *PostModel) Content(ctx context.Context, post *entity.Post, token string if post.MetaKeywords != "" { model["meta_keywords"] = post.MetaKeywords } else if len(tags) > 0 { - meta_keywords := strings.Builder{} - meta_keywords.Write([]byte(tags[0].Name)) + metaKeywords := strings.Builder{} + metaKeywords.Write([]byte(tags[0].Name)) for _, tag := range tags[1:] { - meta_keywords.Write([]byte(",")) - meta_keywords.Write([]byte(tag.Name)) + metaKeywords.Write([]byte(",")) + metaKeywords.Write([]byte(tag.Name)) } - model["meta_keywords"] = meta_keywords.String() + model["meta_keywords"] = metaKeywords.String() } model["is_post"] = true diff --git a/handler/content/model/sheet.go b/handler/content/model/sheet.go index 2897208..2243fc2 100644 --- a/handler/content/model/sheet.go +++ b/handler/content/model/sheet.go @@ -92,13 +92,13 @@ func (s *SheetModel) Content(ctx context.Context, sheet *entity.Post, token stri if sheet.MetaKeywords != "" { model["meta_keywords"] = sheet.MetaKeywords } else if len(tags) > 0 { - meta_keywords := strings.Builder{} - meta_keywords.Write([]byte(tags[0].Name)) + metaKeywords := strings.Builder{} + metaKeywords.Write([]byte(tags[0].Name)) for _, tag := range tags[1:] { - meta_keywords.Write([]byte(",")) - meta_keywords.Write([]byte(tag.Name)) + metaKeywords.Write([]byte(",")) + metaKeywords.Write([]byte(tag.Name)) } - model["meta_keywords"] = meta_keywords.String() + model["meta_keywords"] = metaKeywords.String() } s.SheetService.IncreaseVisit(ctx, sheet.ID) diff --git a/handler/content/model/tag.go b/handler/content/model/tag.go index be1fe72..ce3eb47 100644 --- a/handler/content/model/tag.go +++ b/handler/content/model/tag.go @@ -15,7 +15,6 @@ import ( func NewTagModel(optionService service.OptionService, themeService service.ThemeService, tagService service.TagService, - TagService service.TagService, postTagService service.PostTagService, postAssembler assembler.PostAssembler, ) *TagModel { diff --git a/handler/middleware/log.go b/handler/middleware/log.go index 7f8bcc3..f79e9ed 100644 --- a/handler/middleware/log.go +++ b/handler/middleware/log.go @@ -54,14 +54,13 @@ func (g *GinLoggerMiddleware) LoggerWithConfig(conf GinLoggerConfig) gin.Handler } // Log only when path is not being skipped if _, ok := skip[path]; !ok { - if raw != "" { path = path + "?" + raw } - path = strings.Replace(path, "\n", "", -1) - path = strings.Replace(path, "\r", "", -1) - clientIP := strings.Replace(ctx.ClientIP(), "\n", "", -1) - clientIP = strings.Replace(clientIP, "\r", "", -1) + path = strings.ReplaceAll(path, "\n", "") + path = strings.ReplaceAll(path, "\r", "") + clientIP := strings.ReplaceAll(ctx.ClientIP(), "\n", "") + clientIP = strings.ReplaceAll(clientIP, "\r", "") logger.Info("[GIN]", zap.Time("beginTime", start), diff --git a/handler/middleware/recovery.go b/handler/middleware/recovery.go index 6fba9f2..f27d8dc 100644 --- a/handler/middleware/recovery.go +++ b/handler/middleware/recovery.go @@ -31,7 +31,9 @@ func (r *RecoveryMiddleware) RecoveryWithLogger() gin.HandlerFunc { // Check for a broken connection, as it is not really a // condition that warrants a panic stack trace. var brokenPipe bool + //nolint:errorlint if ne, ok := err.(*net.OpError); ok { + //nolint:errorlint if se, ok := ne.Err.(*os.SyscallError); ok { if strings.Contains(strings.ToLower(se.Error()), "broken pipe") || strings.Contains(strings.ToLower(se.Error()), "connection reset by peer") { brokenPipe = true diff --git a/handler/route.go b/handler/route.go index 512bb36..a1faaa7 100644 --- a/handler/route.go +++ b/handler/route.go @@ -45,15 +45,15 @@ func (s *Server) RegisterRouters() { staticRouter.StaticFS("/themes/", gin.Dir(s.Config.Sonic.ThemeDir, false)) } { - adminApiRouter := router.Group("/api/admin") - adminApiRouter.Use(s.LogMiddleware.LoggerWithConfig(middleware.GinLoggerConfig{}), s.RecoveryMiddleware.RecoveryWithLogger(), s.InstallRedirectMiddleware.InstallRedirect()) - adminApiRouter.GET("/is_installed", s.wrapHandler(s.AdminHandler.IsInstalled)) - adminApiRouter.POST("/login/precheck", s.wrapHandler(s.AdminHandler.AuthPreCheck)) - adminApiRouter.POST("/login", s.wrapHandler(s.AdminHandler.Auth)) - adminApiRouter.POST("/refresh/:refreshToken", s.wrapHandler(s.AdminHandler.RefreshToken)) - adminApiRouter.POST("/installations", s.wrapHandler(s.InstallHandler.InstallBlog)) + adminAPIRouter := router.Group("/api/admin") + adminAPIRouter.Use(s.LogMiddleware.LoggerWithConfig(middleware.GinLoggerConfig{}), s.RecoveryMiddleware.RecoveryWithLogger(), s.InstallRedirectMiddleware.InstallRedirect()) + adminAPIRouter.GET("/is_installed", s.wrapHandler(s.AdminHandler.IsInstalled)) + adminAPIRouter.POST("/login/precheck", s.wrapHandler(s.AdminHandler.AuthPreCheck)) + adminAPIRouter.POST("/login", s.wrapHandler(s.AdminHandler.Auth)) + adminAPIRouter.POST("/refresh/:refreshToken", s.wrapHandler(s.AdminHandler.RefreshToken)) + adminAPIRouter.POST("/installations", s.wrapHandler(s.InstallHandler.InstallBlog)) { - authRouter := adminApiRouter.Group("") + authRouter := adminAPIRouter.Group("") authRouter.Use(s.AuthMiddleware.GetWrapHandler()) authRouter.POST("/logout", s.wrapHandler(s.AdminHandler.LogOut)) authRouter.POST("/password/code", s.wrapHandler(s.AdminHandler.SendResetCode)) diff --git a/handler/server.go b/handler/server.go index 0e12696..b1c4de1 100644 --- a/handler/server.go +++ b/handler/server.go @@ -27,7 +27,7 @@ import ( type Server struct { logger *zap.Logger Config *config.Config - HttpServer *http.Server + HTTPServer *http.Server Router *gin.Engine Template *template.Template AuthMiddleware *middleware.AuthMiddleware @@ -145,7 +145,7 @@ func NewServer(param ServerParams, lifecycle fx.Lifecycle) *Server { s := &Server{ logger: param.Logger, Config: param.Config, - HttpServer: httpServer, + HTTPServer: httpServer, Router: router, Template: param.Template, AuthMiddleware: param.AuthMiddleware, @@ -207,7 +207,7 @@ func (s *Server) Run(ctx context.Context) error { gin.SetMode(gin.DebugMode) } go func() { - if err := s.HttpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed { + if err := s.HTTPServer.ListenAndServe(); err != nil && err != http.ErrServerClosed { // print err info when httpServer start failed s.logger.Error("unexpected error from ListenAndServe", zap.Error(err)) fmt.Printf("http server start error:%s\n", err.Error()) @@ -224,7 +224,7 @@ func (s *Server) wrapHandler(handler wrapperHandler) gin.HandlerFunc { data, err := handler(ctx) if err != nil { s.logger.Error("handler error", zap.Error(err)) - status := xerr.GetHttpStatus(err) + status := xerr.GetHTTPStatus(err) ctx.JSON(status, &dto.BaseDTO{Status: status, Message: xerr.GetMessage(err)}) return } @@ -286,12 +286,12 @@ func (s *Server) wrapTextHandler(handler wrapperHTMLHandler) gin.HandlerFunc { } func (s *Server) handleError(ctx *gin.Context, err error) { - status := xerr.GetHttpStatus(err) + status := xerr.GetHTTPStatus(err) message := xerr.GetMessage(err) model := template.Model{} templateName, _ := s.ThemeService.Render(ctx, strconv.Itoa(status)) - t := s.Template.HtmlTemplate.Lookup(templateName) + t := s.Template.HTMLTemplate.Lookup(templateName) if t == nil { templateName = "common/error/error" } diff --git a/handler/trans/trans.go b/handler/trans/trans.go index 47ebdfc..fb7df9b 100644 --- a/handler/trans/trans.go +++ b/handler/trans/trans.go @@ -37,7 +37,7 @@ func init() { } func Translate(errs validator.ValidationErrors) string { - var errList []string + errList := make([]string, 0, len(errs)) for _, e := range errs { // can translate each error one at a time. errList = append(errList, e.Translate(trans)) diff --git a/log/log.go b/log/log.go index 941c789..1203e54 100644 --- a/log/log.go +++ b/log/log.go @@ -92,6 +92,6 @@ func CtxFatal(ctx context.Context, msg string, fields ...zap.Field) { } func Sync() { - exportUseLogger.Sync() - exportUseSugarLogger.Sync() + _ = exportUseLogger.Sync() + _ = exportUseSugarLogger.Sync() } diff --git a/main.go b/main.go index 67809fd..cf71a5d 100644 --- a/main.go +++ b/main.go @@ -10,7 +10,6 @@ import ( "github.com/go-sonic/sonic/dal" "github.com/go-sonic/sonic/event" "github.com/go-sonic/sonic/event/listener" - _ "github.com/go-sonic/sonic/event/listener" "github.com/go-sonic/sonic/handler" "github.com/go-sonic/sonic/handler/middleware" "github.com/go-sonic/sonic/injection" diff --git a/model/dto/comment.go b/model/dto/comment.go index ad80669..b46daa2 100644 --- a/model/dto/comment.go +++ b/model/dto/comment.go @@ -6,7 +6,7 @@ type Comment struct { ID int32 `json:"id"` Author string `json:"author"` Email string `json:"email"` - IpAddress string `json:"ipAddress"` + IPAddress string `json:"ipAddress"` AuthorURL string `json:"authorUrl"` GravatarMD5 string `json:"gravatarMd5"` Content string `json:"content"` diff --git a/model/param/install.go b/model/param/install.go index 5c92ad4..ca0dcf9 100644 --- a/model/param/install.go +++ b/model/param/install.go @@ -4,5 +4,5 @@ type Install struct { User Locale string `json:"locale"` Title string `json:"title" binding:"required"` - Url string `json:"url"` + URL string `json:"url"` } diff --git a/model/property/attachment.go b/model/property/attachment.go index d2c58d6..fe43912 100644 --- a/model/property/attachment.go +++ b/model/property/attachment.go @@ -222,7 +222,7 @@ var TencentCosBucketName = Property{ Kind: reflect.String, } -var TencentCosSecretId = Property{ +var TencentCosSecretID = Property{ DefaultValue: "", KeyValue: "cos_tencent_secret_id", Kind: reflect.String, diff --git a/model/property/base.go b/model/property/base.go index c3cd7fe..6ba3e5c 100644 --- a/model/property/base.go +++ b/model/property/base.go @@ -43,7 +43,7 @@ var AllProperty = []Property{ BlogLocale, BlogTitle, BlogLogo, - BlogUrl, + BlogURL, BlogFavicon, BlogFooterInfo, EmailHost, @@ -84,12 +84,12 @@ var AllProperty = []Property{ RecycledPostCleaningEnabled, RecycledPostRetentionTime, RecycledPostRetentionTimeunit, - ApiAccessKey, + APIAccessKey, CommentGravatarDefault, CommentNewNeedCheck, CommentNewNotice, CommentReplyNotice, - CommentApiEnabled, + CommentAPIEnabled, CommentPageSize, CommentContentPlaceholder, CommentInternalPluginJs, @@ -128,7 +128,7 @@ var AllProperty = []Property{ TencentCosProtocol, TencentCosRegion, TencentCosBucketName, - TencentCosSecretId, + TencentCosSecretID, TencentCosSecretKey, TencentCosSource, TencentCosStyleRule, diff --git a/model/property/blog.go b/model/property/blog.go index fa4b13d..9fd938a 100644 --- a/model/property/blog.go +++ b/model/property/blog.go @@ -18,7 +18,7 @@ var ( DefaultValue: "", Kind: reflect.String, } - BlogUrl = Property{ + BlogURL = Property{ KeyValue: "blog_url", DefaultValue: "", Kind: reflect.String, diff --git a/model/property/comment.go b/model/property/comment.go index 9544b4b..010569b 100644 --- a/model/property/comment.go +++ b/model/property/comment.go @@ -23,7 +23,7 @@ var ( DefaultValue: false, Kind: reflect.Bool, } - CommentApiEnabled = Property{ + CommentAPIEnabled = Property{ KeyValue: "comment_api_enabled", DefaultValue: true, Kind: reflect.Bool, diff --git a/model/property/other.go b/model/property/other.go index 37038bc..53dcc0f 100644 --- a/model/property/other.go +++ b/model/property/other.go @@ -28,7 +28,7 @@ var ( KeyValue: "default_editor", Kind: reflect.String, } - ApiAccessKey = Property{ + APIAccessKey = Property{ DefaultValue: nil, KeyValue: "api_access_key", Kind: reflect.String, diff --git a/model/property/primary_property.go b/model/property/primary_property.go index cdc74ac..662eec1 100644 --- a/model/property/primary_property.go +++ b/model/property/primary_property.go @@ -14,7 +14,7 @@ var ( } Theme = Property{ KeyValue: "theme", - DefaultValue: consts.DefaultThemeId, + DefaultValue: consts.DefaultThemeID, Kind: reflect.String, } BirthDay = Property{ diff --git a/model/vo/mfa.go b/model/vo/mfa.go index 5398691..58c47e2 100644 --- a/model/vo/mfa.go +++ b/model/vo/mfa.go @@ -4,7 +4,7 @@ import "github.com/go-sonic/sonic/consts" type MFAFactorAuth struct { QRImage string `json:"qrImage"` - OptAuthUrl string `json:"optAuthUrl"` + OptAuthURL string `json:"optAuthUrl"` MFAKey string `json:"mfaKey"` MFAType consts.MFAType `json:"mfaType"` } diff --git a/service/assembler/comment_base.go b/service/assembler/comment_base.go index 8552b4b..904e51d 100644 --- a/service/assembler/comment_base.go +++ b/service/assembler/comment_base.go @@ -82,7 +82,7 @@ func (b *baseCommentAssembler) ConvertToDTO(ctx context.Context, comment *entity ID: comment.ID, Author: comment.Author, Email: comment.Email, - IpAddress: comment.IPAddress, + IPAddress: comment.IPAddress, AuthorURL: comment.AuthorURL, GravatarMD5: comment.GravatarMd5, Content: comment.Content, @@ -116,7 +116,7 @@ func (b *baseCommentAssembler) ConvertToDTOList(ctx context.Context, comments [] ID: comment.ID, Author: comment.Author, Email: comment.Email, - IpAddress: comment.IPAddress, + IPAddress: comment.IPAddress, AuthorURL: comment.AuthorURL, GravatarMD5: comment.GravatarMd5, Content: comment.Content, diff --git a/service/backup.go b/service/backup.go index 5e9ef30..28d48b9 100644 --- a/service/backup.go +++ b/service/backup.go @@ -31,6 +31,6 @@ type BackupType string const ( WholeSite BackupType = "/api/admin/backups/work-dir" - JsonData BackupType = "/api/admin/backups/data" + JSONData BackupType = "/api/admin/backups/data" Markdown BackupType = "/api/admin/backups/markdown/export" ) diff --git a/service/impl/admin.go b/service/impl/admin.go index 9236b7d..a338eb3 100644 --- a/service/impl/admin.go +++ b/service/impl/admin.go @@ -85,7 +85,7 @@ func (a *adminServiceImpl) Auth(ctx context.Context, loginParam param.LoginParam if err != nil { return nil, err } - if a.TwoFactorTOTPMFA.UseMFA(consts.MFAType(user.MfaType)) { + if a.TwoFactorTOTPMFA.UseMFA(user.MfaType) { if len(loginParam.AuthCode) != 6 { return nil, xerr.WithMsg(nil, "请输入6位两步验证码").WithStatus(xerr.StatusBadRequest) } @@ -98,7 +98,7 @@ func (a *adminServiceImpl) Auth(ctx context.Context, loginParam param.LoginParam LogKey: user.Username, LogType: consts.LogTypeLoggedIn, Content: user.Nickname, - IpAddress: util.GetClientIP(ctx), + IPAddress: util.GetClientIP(ctx), }) return a.buildAuthToken(user), nil } @@ -120,7 +120,7 @@ func (a *adminServiceImpl) ClearToken(ctx context.Context) error { LogKey: user.Username, LogType: consts.LogTypeLoggedOut, Content: user.Nickname, - IpAddress: util.GetClientIP(ctx), + IPAddress: util.GetClientIP(ctx), }) return nil } @@ -226,7 +226,6 @@ func (a *adminServiceImpl) GetLogFiles(ctx context.Context, lineNum int64) (stri for position > 0 { if !globalIsPrefix { - position-- _, err = file.Seek(position, 0) @@ -264,7 +263,6 @@ func (a *adminServiceImpl) GetLogFiles(ctx context.Context, lineNum int64) (stri if linesCount == lineNum { break } - } result := bytes.Buffer{} result.Grow(linesTotalByteNum) diff --git a/service/impl/attachment.go b/service/impl/attachment.go index 19046ba..bc452e9 100644 --- a/service/impl/attachment.go +++ b/service/impl/attachment.go @@ -2,6 +2,7 @@ package impl import ( "context" + "errors" "mime/multipart" "os" "strings" @@ -16,13 +17,13 @@ import ( "github.com/go-sonic/sonic/model/entity" "github.com/go-sonic/sonic/model/param" "github.com/go-sonic/sonic/service" - "github.com/go-sonic/sonic/service/file_storage" + "github.com/go-sonic/sonic/service/storage" "github.com/go-sonic/sonic/util/xerr" ) type attachmentServiceImpl struct { OptionService service.OptionService - FileStorageComposite file_storage.FileStorageComposite + FileStorageComposite storage.FileStorageComposite } func (a *attachmentServiceImpl) ConvertToDTOs(ctx context.Context, attachments []*entity.Attachment) ([]*dto.AttachmentDTO, error) { @@ -39,14 +40,14 @@ func (a *attachmentServiceImpl) ConvertToDTOs(ctx context.Context, attachments [ Width: attachment.Width, Height: attachment.Height, Size: attachment.Size, - AttachmentType: consts.AttachmentType(attachment.Type), + AttachmentType: attachment.Type, } dtos = append(dtos, dto) - path, err := a.FileStorageComposite.GetFileStorage(consts.AttachmentType(attachment.Type)).GetFilePath(ctx, attachment.Path) + path, err := a.FileStorageComposite.GetFileStorage(attachment.Type).GetFilePath(ctx, attachment.Path) if err != nil { log.CtxError(ctx, "GetFilePath err", zap.Error(err)) } - thumbPath, err := a.FileStorageComposite.GetFileStorage(consts.AttachmentType(attachment.Type)).GetFilePath(ctx, attachment.ThumbPath) + thumbPath, err := a.FileStorageComposite.GetFileStorage(attachment.Type).GetFilePath(ctx, attachment.ThumbPath) if err != nil { log.CtxError(ctx, "GetFilePath err", zap.Error(err)) } @@ -56,7 +57,7 @@ func (a *attachmentServiceImpl) ConvertToDTOs(ctx context.Context, attachments [ return dtos, nil } -func NewAttachmentService(optionService service.OptionService, fileStorageComposite file_storage.FileStorageComposite) service.AttachmentService { +func NewAttachmentService(optionService service.OptionService, fileStorageComposite storage.FileStorageComposite) service.AttachmentService { return &attachmentServiceImpl{ FileStorageComposite: fileStorageComposite, OptionService: optionService, @@ -75,13 +76,13 @@ func (a *attachmentServiceImpl) ConvertToDTO(ctx context.Context, attachment *en Width: attachment.Width, Height: attachment.Height, Size: attachment.Size, - AttachmentType: consts.AttachmentType(attachment.Type), + AttachmentType: attachment.Type, } - path, err := a.FileStorageComposite.GetFileStorage(consts.AttachmentType(attachment.Type)).GetFilePath(ctx, attachment.Path) + path, err := a.FileStorageComposite.GetFileStorage(attachment.Type).GetFilePath(ctx, attachment.Path) if err != nil { return nil, err } - thumbPath, err := a.FileStorageComposite.GetFileStorage(consts.AttachmentType(attachment.Type)).GetFilePath(ctx, attachment.ThumbPath) + thumbPath, err := a.FileStorageComposite.GetFileStorage(attachment.Type).GetFilePath(ctx, attachment.ThumbPath) if err != nil { return nil, err } @@ -146,7 +147,7 @@ func (a *attachmentServiceImpl) Upload(ctx context.Context, fileHeader *multipar WithStatus(xerr.StatusBadRequest). WithMsg("附件路径为 " + attachmentDTO.Path + " 已经存在") } - if err != nil && err != gorm.ErrRecordNotFound { + if err != nil && errors.Is(err, gorm.ErrRecordNotFound) { return nil, WrapDBErr(err) } attachmentEntity := &entity.Attachment{ @@ -181,7 +182,7 @@ func (a *attachmentServiceImpl) Delete(ctx context.Context, attachmentID int32) if err != nil || result.RowsAffected != 1 { return nil, xerr.WithMsg(err, "delete file failed") } - fileStorage := a.FileStorageComposite.GetFileStorage(consts.AttachmentType(attachment.Type)) + fileStorage := a.FileStorageComposite.GetFileStorage(attachment.Type) err = fileStorage.Delete(ctx, attachment.FileKey) if err != nil { return nil, xerr.WithMsg(err, "delete file failed") @@ -189,10 +190,10 @@ func (a *attachmentServiceImpl) Delete(ctx context.Context, attachmentID int32) return attachment, nil } -func (a *attachmentServiceImpl) DeleteBatch(ctx context.Context, IDs []int32) (attachments []*entity.Attachment, err error) { +func (a *attachmentServiceImpl) DeleteBatch(ctx context.Context, ids []int32) (attachments []*entity.Attachment, err error) { attachments = make([]*entity.Attachment, 0) var globalErr error - for _, id := range IDs { + for _, id := range ids { attachment, err := a.Delete(ctx, id) if err != nil { globalErr = err diff --git a/service/impl/backup.go b/service/impl/backup.go index b6ba10f..91c5e36 100644 --- a/service/impl/backup.go +++ b/service/impl/backup.go @@ -86,11 +86,12 @@ func (b *backupServiceImpl) ListFiles(ctx context.Context, path string, backupTy return nil, xerr.NoType.Wrap(err).WithMsg("Failed to fetch backups") } prefix := "" - if backupType == service.WholeSite { + switch backupType { + case service.WholeSite: prefix = consts.SonicBackupPrefix - } else if backupType == service.JsonData { + case service.JSONData: prefix = consts.SonicDataExportPrefix - } else if backupType == service.Markdown { + case service.Markdown: prefix = consts.SonicBackupMarkdownPrefix } err := filepath.WalkDir(path, func(path string, d fs.DirEntry, err error) error { @@ -198,7 +199,7 @@ func (b *backupServiceImpl) ExportData(ctx context.Context) (*dto.BackupDTO, err if err != nil { return nil, xerr.NoType.Wrap(err).WithMsg("write to file err") } - return b.buildBackupDTO(ctx, string(service.JsonData), filepath.Join(backupFilePath, backupFilename)) + return b.buildBackupDTO(ctx, string(service.JSONData), filepath.Join(backupFilePath, backupFilename)) } func (b *backupServiceImpl) ExportMarkdown(ctx context.Context, needFrontMatter bool) (*dto.BackupDTO, error) { diff --git a/service/impl/base_post.go b/service/impl/base_post.go index 3142f24..e26c84f 100644 --- a/service/impl/base_post.go +++ b/service/impl/base_post.go @@ -114,11 +114,11 @@ func (b basePostServiceImpl) buildPostFullPath(ctx context.Context, post *entity return "", err } if isEnabled { - blogBaseUrl, err := b.OptionService.GetBlogBaseURL(ctx) + blogBaseURL, err := b.OptionService.GetBlogBaseURL(ctx) if err != nil { return "", err } - fullPath.WriteString(blogBaseUrl) + fullPath.WriteString(blogBaseURL) } fullPath.WriteString("/") switch consts.PostPermalinkType(postPermaLinkType.(string)) { @@ -180,11 +180,11 @@ func (b basePostServiceImpl) buildSheetFullPath(ctx context.Context, sheet *enti return "", err } if isEnabled { - blogBaseUrl, err := b.OptionService.GetBlogBaseURL(ctx) + blogBaseURL, err := b.OptionService.GetBlogBaseURL(ctx) if err != nil { return "", err } - fullPath.WriteString(blogBaseUrl) + fullPath.WriteString(blogBaseURL) } fullPath.WriteString("/") switch consts.SheetPermaLinkType(sheetPermaLinkType.(string)) { @@ -212,7 +212,7 @@ func (b basePostServiceImpl) GetByPostID(ctx context.Context, postID int32) (*en var summaryPattern = regexp.MustCompile(`[\t\r\n]`) func (b basePostServiceImpl) GenerateSummary(ctx context.Context, htmlContent string) string { - text := util.CleanHtmlTag(htmlContent) + text := util.CleanHTMLTag(htmlContent) text = summaryPattern.ReplaceAllString(text, "") summaryLength := b.OptionService.GetPostSummaryLength(ctx) end := summaryLength @@ -347,7 +347,6 @@ func (b basePostServiceImpl) CreateOrUpdate(ctx context.Context, post *entity.Po } post.Status = status } - } else { // update post slugCount, err := postDAL.WithContext(ctx).Where(postDAL.Slug.Eq(post.Slug), postDAL.ID.Neq(post.ID)).Count() diff --git a/service/impl/category.go b/service/impl/category.go index 9d37517..2141942 100644 --- a/service/impl/category.go +++ b/service/impl/category.go @@ -152,11 +152,11 @@ func (c categoryServiceImpl) ConvertToCategoryDTO(ctx context.Context, e *entity } fullPath := strings.Builder{} if isEnabled { - blogBaseUrl, err := c.OptionService.GetBlogBaseURL(ctx) + blogBaseURL, err := c.OptionService.GetBlogBaseURL(ctx) if err != nil { return nil, err } - fullPath.WriteString(blogBaseUrl) + fullPath.WriteString(blogBaseURL) } fullPath.WriteString("/") categoryPrefix, err := c.OptionService.GetOrByDefaultWithErr(ctx, property.CategoriesPrefix, "categories") @@ -181,7 +181,7 @@ func (c categoryServiceImpl) ConvertToCategoryDTOs(ctx context.Context, categori if err != nil { return nil, err } - blogBaseUrl, err := c.OptionService.GetBlogBaseURL(ctx) + blogBaseURL, err := c.OptionService.GetBlogBaseURL(ctx) if err != nil { return nil, err } @@ -207,7 +207,7 @@ func (c categoryServiceImpl) ConvertToCategoryDTOs(ctx context.Context, categori fullPath := strings.Builder{} if isEnabled { - fullPath.WriteString(blogBaseUrl) + fullPath.WriteString(blogBaseURL) } fullPath.WriteString("/") fullPath.WriteString(categoryPrefix.(string)) @@ -700,10 +700,8 @@ func (c *categoryUpdateExecutor) refreshPostStatus(ctx context.Context) error { } if status == consts.PostStatusIntimate { needEncryptPostID = append(needEncryptPostID, id) - } else { - if post.Status == consts.PostStatusIntimate && post.Password == "" { - needDecryptPostID = append(needDecryptPostID, id) - } + } else if post.Status == consts.PostStatusIntimate && post.Password == "" { + needDecryptPostID = append(needDecryptPostID, id) } } if len(needEncryptPostID) > 0 { diff --git a/service/impl/client_option.go b/service/impl/client_option.go index f1739df..14fccb4 100644 --- a/service/impl/client_option.go +++ b/service/impl/client_option.go @@ -56,7 +56,7 @@ func (c *clientOptionServiceImpl) getPrivateOption() map[string]struct{} { property.EmailUsername, property.EmailPassword, property.EmailFromName, - property.ApiAccessKey, + property.APIAccessKey, property.MinioEndpoint, property.MinioBucketName, property.MinioAccessKey, @@ -86,7 +86,7 @@ func (c *clientOptionServiceImpl) getPrivateOption() map[string]struct{} { property.TencentCosProtocol, property.TencentCosRegion, property.TencentCosBucketName, - property.TencentCosSecretId, + property.TencentCosSecretID, property.TencentCosSecretKey, property.TencentCosSource, property.TencentCosStyleRule, diff --git a/service/impl/comment_base.go b/service/impl/comment_base.go index bbed007..e711bb7 100644 --- a/service/impl/comment_base.go +++ b/service/impl/comment_base.go @@ -319,7 +319,7 @@ func (*baseCommentServiceImpl) CountChildren(ctx context.Context, parentCommentI } func (b *baseCommentServiceImpl) GetChildren(ctx context.Context, parentCommentID int32, contentID int32, commentType consts.CommentType) ([]*entity.Comment, error) { - allComments, err := b.GetByContentID(ctx, int32(contentID), commentType, nil) + allComments, err := b.GetByContentID(ctx, contentID, commentType, nil) if err != nil { return nil, err } diff --git a/service/impl/comment_post.go b/service/impl/comment_post.go index 5b6d3e8..7ac3861 100644 --- a/service/impl/comment_post.go +++ b/service/impl/comment_post.go @@ -2,6 +2,7 @@ package impl import ( "context" + "errors" "gorm.io/gorm" @@ -26,7 +27,7 @@ func NewPostCommentService(baseCommentService service.BaseCommentService) servic func (p postCommentServiceImpl) CreateBy(ctx context.Context, commentParam *param.Comment) (*entity.Comment, error) { postDAL := dal.GetQueryByCtx(ctx).Post post, err := postDAL.WithContext(ctx).Where(postDAL.ID.Eq(commentParam.PostID)).First() - if err == gorm.ErrRecordNotFound { + if errors.Is(err, gorm.ErrRecordNotFound) { return nil, xerr.WithMsg(nil, "post not found").WithStatus(xerr.StatusBadRequest) } if err != nil { diff --git a/service/impl/common.go b/service/impl/common.go index fee527d..d7513e5 100644 --- a/service/impl/common.go +++ b/service/impl/common.go @@ -1,6 +1,7 @@ package impl import ( + "errors" "reflect" "strings" "unicode" @@ -16,7 +17,7 @@ func WrapDBErr(err error) error { if err == nil { return nil } - if err == gorm.ErrRecordNotFound { + if errors.Is(err, gorm.ErrRecordNotFound) { return xerr.NoRecord.Wrap(err).WithMsg("The resource does not exist or has been deleted").WithStatus(xerr.StatusNotFound) } return xerr.DB.Wrap(err).WithStatus(xerr.StatusInternalServerError) @@ -100,13 +101,16 @@ func ConvertSort(sorts *param.Sort) ([]*Order, error) { if len(items) == 2 { order.Property = UnderscoreName(items[0]) items[1] = strings.ToLower(items[1]) - if items[1] == "asc" { + + switch items[1] { + case "asc": order.Asc = true - } else if items[1] == "desc" { + case "desc": order.Asc = false - } else { + default: return nil, xerr.WithStatus(nil, xerr.StatusBadRequest).WithMsg("sort parameter error") } + result = append(result, &order) } } diff --git a/service/impl/export_import.go b/service/impl/export_import.go index 50dceaf..ea7c454 100644 --- a/service/impl/export_import.go +++ b/service/impl/export_import.go @@ -380,7 +380,7 @@ func convertJekyllMetaData(metadata map[string]any, postName string, postDate ti func convertJekyllContent(metadata map[string]any, content string) string { lines := strings.Split(content, "\n") - var resultLines []string + resultLines := make([]string, 0, len(lines)) for _, line := range lines { resultLines = append(resultLines, strings.Trim(line, "\r\n")) } diff --git a/service/impl/init.go b/service/impl/init.go index 7048baa..826cf75 100644 --- a/service/impl/init.go +++ b/service/impl/init.go @@ -2,7 +2,7 @@ package impl import ( "github.com/go-sonic/sonic/injection" - "github.com/go-sonic/sonic/service/file_storage" + "github.com/go-sonic/sonic/service/storage" ) func init() { @@ -39,6 +39,6 @@ func init() { NewThemeService, NewUserService, NewExportImport, - file_storage.NewFileStorageComposite, + storage.NewFileStorageComposite, ) } diff --git a/service/impl/install.go b/service/impl/install.go index bde5bb7..9369583 100644 --- a/service/impl/install.go +++ b/service/impl/install.go @@ -110,14 +110,14 @@ func (i installServiceImpl) createDefaultSetting(ctx context.Context, installPar optionMap[property.IsInstalled.KeyValue] = "true" optionMap[property.GlobalAbsolutePathEnabled.KeyValue] = "false" optionMap[property.BlogTitle.KeyValue] = installParam.Title - if installParam.Url == "" { + if installParam.URL == "" { blogURL, err := i.OptionService.GetBlogBaseURL(ctx) if err != nil { return err } - optionMap[property.BlogUrl.KeyValue] = blogURL + optionMap[property.BlogURL.KeyValue] = blogURL } else { - optionMap[property.BlogUrl.KeyValue] = installParam.Url + optionMap[property.BlogURL.KeyValue] = installParam.URL } if installParam.Locale == "" { optionMap[property.BlogLocale.KeyValue] = property.BlogLocale.DefaultValue.(string) diff --git a/service/impl/log.go b/service/impl/log.go index 288322f..92331d8 100644 --- a/service/impl/log.go +++ b/service/impl/log.go @@ -3,7 +3,6 @@ package impl import ( "context" - "github.com/go-sonic/sonic/consts" "github.com/go-sonic/sonic/dal" "github.com/go-sonic/sonic/model/dto" "github.com/go-sonic/sonic/model/entity" @@ -45,7 +44,7 @@ func (l *logServiceImpl) ConvertToDTO(log *entity.Log) *dto.Log { return &dto.Log{ ID: log.ID, LogKey: log.LogKey, - LogType: consts.LogType(log.Type), + LogType: log.Type, Content: log.Content, IPAddress: log.IPAddress, CreateTime: log.CreateTime.UnixMilli(), diff --git a/service/impl/option.go b/service/impl/option.go index 7b1ac89..a313146 100644 --- a/service/impl/option.go +++ b/service/impl/option.go @@ -68,13 +68,13 @@ func (o *optionServiceImpl) GetPostSummaryLength(ctx context.Context) int { func (o *optionServiceImpl) GetPostSort(ctx context.Context) param.Sort { p := property.IndexSort value, err := o.getFromCacheMissFromDB(ctx, p) - var sort string + sort := p.DefaultValue.(string) + + //nolint:gocritic if xerr.GetType(err) == xerr.NoRecord { o.Cache.SetDefault(p.KeyValue, p.DefaultValue) - sort = p.DefaultValue.(string) } else if err != nil { log.CtxErrorf(ctx, "query option err=%v", err) - sort = p.DefaultValue.(string) } else { sort = value.(string) } @@ -88,10 +88,10 @@ func (o *optionServiceImpl) GetIndexPageSize(ctx context.Context) int { value, err := o.getFromCacheMissFromDB(ctx, p) if xerr.GetType(err) == xerr.NoRecord { o.Cache.SetDefault(p.KeyValue, p.DefaultValue) - return int(p.DefaultValue.(int)) + return p.DefaultValue.(int) } else if err != nil { log.CtxErrorf(ctx, "query option err=%v", err) - return int(p.DefaultValue.(int)) + return p.DefaultValue.(int) } return value.(int) } @@ -121,7 +121,7 @@ func (o *optionServiceImpl) GetOrByDefaultWithErr(ctx context.Context, p propert } func (o *optionServiceImpl) GetBlogBaseURL(ctx context.Context) (string, error) { - blogURL, err := o.GetOrByDefaultWithErr(ctx, property.BlogUrl, "") + blogURL, err := o.GetOrByDefaultWithErr(ctx, property.BlogURL, "") if err != nil { return "", err } @@ -364,7 +364,7 @@ func (o *optionServiceImpl) GetJournalPrefix(ctx context.Context) (string, error return value.(string), nil } -func (o *optionServiceImpl) GetActivatedThemeId(ctx context.Context) (string, error) { +func (o *optionServiceImpl) GetActivatedThemeID(ctx context.Context) (string, error) { p := property.Theme value, err := o.getFromCacheMissFromDB(ctx, p) if xerr.GetType(err) == xerr.NoRecord { diff --git a/service/impl/post.go b/service/impl/post.go index 6366607..fa99f08 100644 --- a/service/impl/post.go +++ b/service/impl/post.go @@ -3,6 +3,7 @@ package impl import ( "context" "database/sql/driver" + "errors" "net/url" "strconv" "strings" @@ -116,7 +117,7 @@ func (p postServiceImpl) Create(ctx context.Context, postParam *param.Post) (*en LogKey: strconv.Itoa(int(post.ID)), LogType: consts.LogTypePostPublished, Content: post.Title, - IpAddress: util.GetClientIP(ctx), + IPAddress: util.GetClientIP(ctx), }) return post, nil } @@ -147,7 +148,7 @@ func (p postServiceImpl) Update(ctx context.Context, postID int32, postParam *pa LogKey: strconv.Itoa(int(post.ID)), LogType: consts.LogTypePostEdited, Content: post.Title, - IpAddress: util.GetClientIP(ctx), + IPAddress: util.GetClientIP(ctx), }) return post, nil } @@ -181,7 +182,7 @@ func (p postServiceImpl) ConvertParam(ctx context.Context, postParam *param.Post post.UpdateTime = util.TimePtr(time.UnixMilli(*postParam.UpdateTime)) } - post.WordCount = util.HtmlFormatWordCount(post.FormatContent) + post.WordCount = util.HTMLFormatWordCount(post.FormatContent) if postParam.Slug == "" { post.Slug = util.Slug(postParam.Title) } else { @@ -262,25 +263,24 @@ func (p postServiceImpl) GetPrevPosts(ctx context.Context, post *entity.Post, si postDAL := dal.GetQueryByCtx(ctx).Post postDO := postDAL.WithContext(ctx).Where(postDAL.Status.Eq(consts.PostStatusPublished)) - if postSort == "createTime" { + switch postSort { + case "createTime": postDO = postDO.Where(postDAL.CreateTime.Gt(post.CreateTime)).Order(postDAL.CreateTime) - } else if postSort == "editTime" { - var editTime time.Time - if post.EditTime == nil { - editTime = post.CreateTime - } else { + case "editTime": + editTime := post.CreateTime + if post.EditTime != nil { editTime = *post.EditTime } postDO = postDO.Where(postDAL.EditTime.Gt(editTime)).Order(postDAL.EditTime) - } else if postSort == "visits" { + case "visits": postDO = postDO.Where(postDAL.Visits.Gt(post.Visits)).Order(postDAL.EditTime) - } else { + default: return nil, nil } posts, err := postDO.Find() if err != nil { - if err == gorm.ErrRecordNotFound { + if errors.Is(err, gorm.ErrRecordNotFound) { return nil, nil } return nil, WrapDBErr(err) @@ -293,19 +293,18 @@ func (p postServiceImpl) GetNextPosts(ctx context.Context, post *entity.Post, si postDAL := dal.GetQueryByCtx(ctx).Post postDO := postDAL.WithContext(ctx).Where(postDAL.Status.Eq(consts.PostStatusPublished)) - if postSort == "createTime" { + switch postSort { + case "createTime": postDO = postDO.Where(postDAL.CreateTime.Lt(post.CreateTime)).Order(postDAL.CreateTime.Desc()) - } else if postSort == "editTime" { - var editTime time.Time - if post.EditTime == nil { - editTime = post.CreateTime - } else { + case "editTime": + editTime := post.CreateTime + if post.EditTime != nil { editTime = *post.EditTime } postDO = postDO.Where(postDAL.EditTime.Lt(editTime)).Order(postDAL.EditTime.Desc()) - } else if postSort == "visits" { + case "visits": postDO = postDO.Where(postDAL.Visits.Lt(post.Visits)).Order(postDAL.EditTime.Desc()) - } else { + default: return nil, nil } diff --git a/service/impl/sheet.go b/service/impl/sheet.go index c384c80..57816e1 100644 --- a/service/impl/sheet.go +++ b/service/impl/sheet.go @@ -96,7 +96,7 @@ func (s sheetServiceImpl) ConvertParam(ctx context.Context, sheetParam *param.Sh sheet.EditorType = consts.EditorTypeMarkdown } - sheet.WordCount = util.HtmlFormatWordCount(sheet.FormatContent) + sheet.WordCount = util.HTMLFormatWordCount(sheet.FormatContent) if sheetParam.Slug == "" { sheet.Slug = util.Slug(sheetParam.Title) } else { @@ -135,7 +135,7 @@ func (s sheetServiceImpl) Update(ctx context.Context, sheetID int32, sheetParam LogKey: strconv.Itoa(int(sheet.ID)), LogType: consts.LogTypeSheetEdited, Content: sheet.Title, - IpAddress: util.GetClientIP(ctx), + IPAddress: util.GetClientIP(ctx), }) return sheet, nil } diff --git a/service/impl/tag.go b/service/impl/tag.go index b32051c..df6ca48 100644 --- a/service/impl/tag.go +++ b/service/impl/tag.go @@ -142,11 +142,11 @@ func (t tagServiceImpl) ConvertToDTO(ctx context.Context, tag *entity.Tag) (*dto return nil, err } if isEnabled { - blogBaseUrl, err := t.OptionService.GetBlogBaseURL(ctx) + blogBaseURL, err := t.OptionService.GetBlogBaseURL(ctx) if err != nil { return nil, err } - fullPath.WriteString(blogBaseUrl) + fullPath.WriteString(blogBaseURL) } fullPath.WriteString("/") @@ -171,9 +171,9 @@ func (t tagServiceImpl) ConvertToDTOs(ctx context.Context, tags []*entity.Tag) ( if err != nil { return nil, err } - var blogBaseUrl string + var blogBaseURL string if isEnabled { - blogBaseUrl, err = t.OptionService.GetBlogBaseURL(ctx) + blogBaseURL, err = t.OptionService.GetBlogBaseURL(ctx) if err != nil { return nil, err } @@ -191,7 +191,7 @@ func (t tagServiceImpl) ConvertToDTOs(ctx context.Context, tags []*entity.Tag) ( for _, tag := range tags { fullPath := strings.Builder{} if isEnabled { - fullPath.WriteString(blogBaseUrl) + fullPath.WriteString(blogBaseURL) } fullPath.WriteString("/") fullPath.WriteString(tagPrefix.(string)) diff --git a/service/impl/theme.go b/service/impl/theme.go index cfa9ebc..de8a7d2 100644 --- a/service/impl/theme.go +++ b/service/impl/theme.go @@ -42,7 +42,7 @@ func NewThemeService(optionService service.OptionService, config *config.Config, } func (t *themeServiceImpl) GetActivateTheme(ctx context.Context) (*dto.ThemeProperty, error) { - activatedThemeID, err := t.OptionService.GetActivatedThemeId(ctx) + activatedThemeID, err := t.OptionService.GetActivatedThemeID(ctx) if err != nil { return nil, err } @@ -57,7 +57,7 @@ func (t *themeServiceImpl) GetThemeByID(ctx context.Context, themeID string) (*d if themeProperty == nil { return nil, xerr.WithStatus(nil, xerr.StatusBadRequest).WithMsg(themeID + " not exist") } - activatedThemeID, err := t.OptionService.GetActivatedThemeId(ctx) + activatedThemeID, err := t.OptionService.GetActivatedThemeID(ctx) if err != nil { return nil, err } @@ -72,7 +72,7 @@ func (t *themeServiceImpl) ListAllTheme(ctx context.Context) ([]*dto.ThemeProper if err != nil { return nil, err } - activatedThemeID, err := t.OptionService.GetActivatedThemeId(ctx) + activatedThemeID, err := t.OptionService.GetActivatedThemeID(ctx) if err != nil { return nil, err } @@ -351,7 +351,7 @@ func (t *themeServiceImpl) SaveThemeSettings(ctx context.Context, themeID string } func (t *themeServiceImpl) DeleteThemeSettings(ctx context.Context, themeID string) error { - activatedThemeID, err := t.OptionService.GetActivatedThemeId(ctx) + activatedThemeID, err := t.OptionService.GetActivatedThemeID(ctx) if err != nil { return err } @@ -365,7 +365,7 @@ func (t *themeServiceImpl) DeleteThemeSettings(ctx context.Context, themeID stri } func (t *themeServiceImpl) DeleteTheme(ctx context.Context, themeID string, deleteSettings bool) error { - activatedThemeID, err := t.OptionService.GetActivatedThemeId(ctx) + activatedThemeID, err := t.OptionService.GetActivatedThemeID(ctx) if err != nil { return err } @@ -420,7 +420,7 @@ func (t *themeServiceImpl) ReloadTheme(ctx context.Context) error { } func (t *themeServiceImpl) TemplateExist(ctx context.Context, template string) (bool, error) { - activatedThemeID, err := t.OptionService.GetActivatedThemeId(ctx) + activatedThemeID, err := t.OptionService.GetActivatedThemeID(ctx) if err != nil { return false, err } @@ -462,7 +462,7 @@ func (t *themeServiceImpl) addTheme(ctx context.Context, themeProperty *dto.Them } func (t *themeServiceImpl) Render(ctx context.Context, name string) (string, error) { - activatedThemeID, err := t.OptionService.GetActivatedThemeId(ctx) + activatedThemeID, err := t.OptionService.GetActivatedThemeID(ctx) if err != nil { return "", err } diff --git a/service/option.go b/service/option.go index c5826cf..028f49c 100644 --- a/service/option.go +++ b/service/option.go @@ -21,7 +21,7 @@ type OptionService interface { GetLinksPrefix(ctx context.Context) (string, error) GetPhotoPrefix(ctx context.Context) (string, error) GetJournalPrefix(ctx context.Context) (string, error) - GetActivatedThemeId(ctx context.Context) (string, error) + GetActivatedThemeID(ctx context.Context) (string, error) GetPostPermalinkType(ctx context.Context) (consts.PostPermalinkType, error) GetSheetPermalinkType(ctx context.Context) (consts.SheetPermaLinkType, error) GetIndexPageSize(ctx context.Context) int diff --git a/service/file_storage/file_storage_impl/aliyun.go b/service/storage/impl/aliyun.go similarity index 99% rename from service/file_storage/file_storage_impl/aliyun.go rename to service/storage/impl/aliyun.go index b4e484b..188fb0e 100644 --- a/service/file_storage/file_storage_impl/aliyun.go +++ b/service/storage/impl/aliyun.go @@ -1,4 +1,4 @@ -package file_storage_impl +package filestorageimpl import ( "context" diff --git a/service/file_storage/file_storage_impl/common.go b/service/storage/impl/common.go similarity index 98% rename from service/file_storage/file_storage_impl/common.go rename to service/storage/impl/common.go index 4559e31..61e6ceb 100644 --- a/service/file_storage/file_storage_impl/common.go +++ b/service/storage/impl/common.go @@ -1,4 +1,4 @@ -package file_storage_impl +package filestorageimpl import ( "context" diff --git a/service/file_storage/file_storage_impl/file_descriptor.go b/service/storage/impl/file_descriptor.go similarity index 99% rename from service/file_storage/file_storage_impl/file_descriptor.go rename to service/storage/impl/file_descriptor.go index 26e6e2a..37d8753 100644 --- a/service/file_storage/file_storage_impl/file_descriptor.go +++ b/service/storage/impl/file_descriptor.go @@ -1,4 +1,4 @@ -package file_storage_impl +package filestorageimpl import ( "path/filepath" diff --git a/service/file_storage/file_storage_impl/init.go b/service/storage/impl/init.go similarity index 83% rename from service/file_storage/file_storage_impl/init.go rename to service/storage/impl/init.go index 45d0b93..f71c9a1 100644 --- a/service/file_storage/file_storage_impl/init.go +++ b/service/storage/impl/init.go @@ -1,4 +1,4 @@ -package file_storage_impl +package filestorageimpl import "github.com/go-sonic/sonic/injection" diff --git a/service/file_storage/file_storage_impl/local.go b/service/storage/impl/local.go similarity index 96% rename from service/file_storage/file_storage_impl/local.go rename to service/storage/impl/local.go index d9f2529..e26c9dd 100644 --- a/service/file_storage/file_storage_impl/local.go +++ b/service/storage/impl/local.go @@ -1,4 +1,4 @@ -package file_storage_impl +package filestorageimpl import ( "context" @@ -165,12 +165,12 @@ func (l *LocalFileStorage) GetAttachmentType() consts.AttachmentType { func (l *LocalFileStorage) GetFilePath(ctx context.Context, relativePath string) (string, error) { isEnabled, _ := l.OptionService.IsEnabledAbsolutePath(ctx) - var blogBaseUrl string + var blogBaseURL string if isEnabled { - blogBaseUrl, _ = l.OptionService.GetBlogBaseURL(ctx) + blogBaseURL, _ = l.OptionService.GetBlogBaseURL(ctx) } - fullPath, _ := url.JoinPath(blogBaseUrl, relativePath) - if blogBaseUrl == "" { + fullPath, _ := url.JoinPath(blogBaseURL, relativePath) + if blogBaseURL == "" { fullPath, _ = url.JoinPath("/", relativePath) } fullPath, _ = url.PathUnescape(fullPath) diff --git a/service/file_storage/file_storage_impl/minio.go b/service/storage/impl/minio.go similarity index 99% rename from service/file_storage/file_storage_impl/minio.go rename to service/storage/impl/minio.go index 0c8b551..efaf2af 100644 --- a/service/file_storage/file_storage_impl/minio.go +++ b/service/storage/impl/minio.go @@ -1,4 +1,4 @@ -package file_storage_impl +package filestorageimpl import ( "context" diff --git a/service/file_storage/file_storage_impl/url_file_descriptor.go b/service/storage/impl/url_file_descriptor.go similarity index 98% rename from service/file_storage/file_storage_impl/url_file_descriptor.go rename to service/storage/impl/url_file_descriptor.go index 318c6c7..5df1dc3 100644 --- a/service/file_storage/file_storage_impl/url_file_descriptor.go +++ b/service/storage/impl/url_file_descriptor.go @@ -1,4 +1,4 @@ -package file_storage_impl +package filestorageimpl import ( "net/url" diff --git a/service/file_storage/file_storage.go b/service/storage/storage.go similarity index 71% rename from service/file_storage/file_storage.go rename to service/storage/storage.go index 9e636ac..f7959fa 100644 --- a/service/file_storage/file_storage.go +++ b/service/storage/storage.go @@ -1,4 +1,4 @@ -package file_storage +package storage import ( "context" @@ -6,7 +6,7 @@ import ( "github.com/go-sonic/sonic/consts" "github.com/go-sonic/sonic/model/dto" - "github.com/go-sonic/sonic/service/file_storage/file_storage_impl" + storageimpl "github.com/go-sonic/sonic/service/storage/impl" ) type FileStorage interface { @@ -20,12 +20,12 @@ type FileStorageComposite interface { GetFileStorage(storageType consts.AttachmentType) FileStorage } type fileStorageComposite struct { - localStorage *file_storage_impl.LocalFileStorage - minio *file_storage_impl.MinIO - aliyunOSS *file_storage_impl.Aliyun + localStorage *storageimpl.LocalFileStorage + minio *storageimpl.MinIO + aliyunOSS *storageimpl.Aliyun } -func NewFileStorageComposite(localStorage *file_storage_impl.LocalFileStorage, minio *file_storage_impl.MinIO, aliyun *file_storage_impl.Aliyun) FileStorageComposite { +func NewFileStorageComposite(localStorage *storageimpl.LocalFileStorage, minio *storageimpl.MinIO, aliyun *storageimpl.Aliyun) FileStorageComposite { return &fileStorageComposite{ localStorage: localStorage, minio: minio, diff --git a/service/theme/property_scanner.go b/service/theme/property_scanner.go index 175fb42..f4fff61 100644 --- a/service/theme/property_scanner.go +++ b/service/theme/property_scanner.go @@ -48,15 +48,20 @@ func (s *propertyScannerImpl) GetThemeByThemeID(ctx context.Context, themeID str return nil, nil } -func (s *propertyScannerImpl) ListAll(ctx context.Context, themeRootPath string) ([]*dto.ThemeProperty, error) { +func (s *propertyScannerImpl) ListAll(ctx context.Context, themeRootPath string) (themes []*dto.ThemeProperty, err error) { themeRootDir, err := os.Open(themeRootPath) - defer themeRootDir.Close() if err != nil { return nil, xerr.NoType.Wrap(err) } + defer func() { + _ = themeRootDir.Close() + }() + themeDirs, err := themeRootDir.ReadDir(0) - result := make([]*dto.ThemeProperty, 0) + if err != nil { + return + } for _, themeDir := range themeDirs { if themeDir.IsDir() { @@ -64,11 +69,11 @@ func (s *propertyScannerImpl) ListAll(ctx context.Context, themeRootPath string) if err != nil { return nil, err } - result = append(result, themeProperty) + themes = append(themes, themeProperty) } } - return result, nil + return } func (s *propertyScannerImpl) ReadThemeProperty(ctx context.Context, themePath string) (*dto.ThemeProperty, error) { @@ -79,10 +84,11 @@ func (s *propertyScannerImpl) ReadThemeProperty(ctx context.Context, themePath s ) for _, themePropertyFilename := range consts.ThemePropertyFilenames { themePropertyFile, err = os.Open(filepath.Join(themePath, themePropertyFilename)) - defer themePropertyFile.Close() + if os.IsNotExist(err) { continue } + defer themePropertyFile.Close() fileStat, err = themePropertyFile.Stat() if err != nil { continue @@ -107,7 +113,7 @@ func (s *propertyScannerImpl) ReadThemeProperty(ctx context.Context, themePath s themeProperty.ThemePath = themePath themeProperty.FolderName = filepath.Base(themePath) themeProperty.Activated = false - hasOptions, _ := s.hasSettingFile(ctx, themePath) + hasOptions, _ := s.hasSettingFile(themePath) themeProperty.HasOptions = hasOptions screenshotFilename, err := s.GetThemeScreenshotAbsPath(ctx, themePath) if err != nil { @@ -128,10 +134,12 @@ func (s *propertyScannerImpl) UnmarshalProperty(ctx context.Context, themeProper func (s *propertyScannerImpl) GetThemeScreenshotAbsPath(ctx context.Context, themePath string) (string, error) { themeDir, err := os.Open(themePath) - defer themeDir.Close() if err != nil { return "", xerr.NoType.Wrapf(err, "open theme path error themePath=%s", themePath) } + + defer themeDir.Close() + themeFiles, err := themeDir.ReadDir(0) if err != nil { return "", xerr.NoType.Wrapf(err, "read theme file error themePath=%s", themePath) @@ -150,7 +158,7 @@ func (s *propertyScannerImpl) GetThemeScreenshotAbsPath(ctx context.Context, the return "", nil } -func (s *propertyScannerImpl) hasSettingFile(ctx context.Context, themePath string) (bool, error) { +func (s *propertyScannerImpl) hasSettingFile(themePath string) (bool, error) { var ( err error themeSettingFileInfo os.FileInfo @@ -180,10 +188,12 @@ func (s *propertyScannerImpl) ReadThemeConfig(ctx context.Context, themePath str ) for _, themeSettingFilename := range consts.ThemeSettingFilenames { themeSettingFile, err = os.Open(filepath.Join(themePath, themeSettingFilename)) - defer themeSettingFile.Close() if os.IsNotExist(err) { continue } + + defer themeSettingFile.Close() + fileStat, err = themeSettingFile.Stat() if err != nil { continue diff --git a/service/theme/theme_fetcher.go b/service/theme/theme_fetcher.go index fd7c556..ace794b 100644 --- a/service/theme/theme_fetcher.go +++ b/service/theme/theme_fetcher.go @@ -2,6 +2,7 @@ package theme import ( "context" + "errors" "io" "mime/multipart" "os" @@ -54,7 +55,7 @@ func (m *multipartZipThemeFetcherImpl) FetchTheme(ctx context.Context, file inte } diskFile, err := os.OpenFile(diskFilePath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o444) - if err != nil && err != os.ErrExist { + if !errors.Is(err, os.ErrExist) { return nil, xerr.WithStatus(err, xerr.StatusInternalServerError).WithMsg("create file error") } defer diskFile.Close() diff --git a/template/extension/post.go b/template/extension/post.go index c9f6ea3..be3e790 100644 --- a/template/extension/post.go +++ b/template/extension/post.go @@ -35,7 +35,7 @@ func RegisterPostFunc(template *template.Template, postService service.PostServi p.addGetPostCount() p.addGetPostArchiveYear() p.addGetPostArchiveMonth() - p.addListPostByCategoryId() + p.addListPostByCategoryID() p.addListPostByCategorySlug() p.addListPostByTagID() p.addListPostByTagSlug() @@ -94,8 +94,8 @@ func (p *postExtension) addGetPostArchiveMonth() { p.Template.AddFunc("listYearArchives", getPostArchiveMonthFunc) } -func (p *postExtension) addListPostByCategoryId() { - listPostByCategoryId := func(categoryID int32) ([]*vo.Post, error) { +func (p *postExtension) addListPostByCategoryID() { + listPostByCategoryID := func(categoryID int32) ([]*vo.Post, error) { ctx := context.Background() posts, err := p.PostCategoryService.ListByCategoryID(ctx, categoryID, consts.PostStatusPublished) if err != nil { @@ -103,7 +103,7 @@ func (p *postExtension) addListPostByCategoryId() { } return p.PostAssembler.ConvertToListVO(ctx, posts) } - p.Template.AddFunc("listPostByCategoryID", listPostByCategoryId) + p.Template.AddFunc("listPostByCategoryID", listPostByCategoryID) } func (p *postExtension) addListPostByCategorySlug() { diff --git a/template/extension/tool.go b/template/extension/tool.go index 52c8d0c..3fe0698 100644 --- a/template/extension/tool.go +++ b/template/extension/tool.go @@ -22,10 +22,7 @@ func RegisterToolFunc(template *template.Template) { // addRainbow 彩虹分页算法 func (t *toolExtension) addRainbow() { - rainbowPage := func(page, total, display int) []int { - return util.RainbowPage(page, total, display) - } - t.Template.AddFunc("rainbowPage", rainbowPage) + t.Template.AddFunc("rainbowPage", util.RainbowPage) } func (t *toolExtension) addRandom() { diff --git a/template/template.go b/template/template.go index 4227e94..f686e12 100644 --- a/template/template.go +++ b/template/template.go @@ -19,7 +19,7 @@ import ( ) type Template struct { - HtmlTemplate *htmlTemplate.Template + HTMLTemplate *htmlTemplate.Template TextTemplate *template.Template sharedVariable map[string]any lock sync.RWMutex @@ -59,8 +59,7 @@ func (t *Template) Load(paths []string) error { t.paths = paths filenames := make([]string, 0) for _, templateDir := range paths { - - err := filepath.Walk(templateDir, func(path string, info fs.FileInfo, err error) error { + err := filepath.Walk(templateDir, func(path string, _ fs.FileInfo, _ error) error { if filepath.Ext(path) == ".tmpl" { filenames = append(filenames, path) if err := t.watcher.Add(path); err != nil { @@ -84,7 +83,7 @@ func (t *Template) Load(paths []string) error { return xerr.WithMsg(err, "parse template err").WithStatus(xerr.StatusInternalServerError) } t.TextTemplate = tt - t.HtmlTemplate = ht + t.HTMLTemplate = ht return nil } @@ -95,51 +94,35 @@ func (t *Template) SetSharedVariable(name string, value interface{}) { } func (t *Template) Execute(wr io.Writer, data Model) error { - dataMap, err := t.wrapData(data) - if err != nil { - return err - } - return t.HtmlTemplate.Execute(wr, dataMap) + return t.HTMLTemplate.Execute(wr, t.wrapData(data)) } func (t *Template) ExecuteTemplate(wr io.Writer, name string, data Model) error { - dataMap, err := t.wrapData(data) - if err != nil { - return err - } - return t.HtmlTemplate.ExecuteTemplate(wr, name, dataMap) + return t.HTMLTemplate.ExecuteTemplate(wr, name, t.wrapData(data)) } func (t *Template) ExecuteText(wr io.Writer, data Model) error { - dataMap, err := t.wrapData(data) - if err != nil { - return err - } - return t.TextTemplate.Execute(wr, dataMap) + return t.TextTemplate.Execute(wr, t.wrapData(data)) } func (t *Template) ExecuteTextTemplate(wr io.Writer, name string, data Model) error { - dataMap, err := t.wrapData(data) - if err != nil { - return err - } - return t.TextTemplate.ExecuteTemplate(wr, name, dataMap) + return t.TextTemplate.ExecuteTemplate(wr, name, t.wrapData(data)) } -func (t *Template) wrapData(data Model) (map[string]any, error) { +func (t *Template) wrapData(data Model) map[string]any { if data == nil { - return nil, nil + return nil } t.lock.RLock() defer t.lock.RUnlock() data.MergeAttributes(t.sharedVariable) data["now"] = time.Now() - return data, nil + return data } func (t *Template) AddFunc(name string, fn interface{}) { - if t.HtmlTemplate != nil { + if t.HTMLTemplate != nil { panic("the template has been parsed") } t.funcMap[name] = fn diff --git a/template/watcher.go b/template/watcher.go index 5275029..a0b6619 100644 --- a/template/watcher.go +++ b/template/watcher.go @@ -18,13 +18,15 @@ func (t *Template) Watch() { continue } - if event.Op&fsnotify.Write == fsnotify.Write { + switch { + case event.Op&fsnotify.Write == fsnotify.Write: t.logger.Info("Write file:", zap.String("file", event.Name)) - } else if event.Op&fsnotify.Create == fsnotify.Create { + case event.Op&fsnotify.Create == fsnotify.Create: t.logger.Info("Create file:", zap.String("file", event.Name)) - } else { + default: continue } + err := t.Reload([]string{event.Name}) if err != nil { t.logger.Error("reload template error", zap.Error(err)) diff --git a/util/common.go b/util/common.go index ea78890..36a4a6f 100644 --- a/util/common.go +++ b/util/common.go @@ -32,7 +32,7 @@ func CompositeURL(urls ...string) string { var htmlRegexp = regexp.MustCompile(`(<[^<]*?>)|(<[\s]*?/[^<]*?>)|(<[^<]*?/[\s]*?>)`) -func CleanHtmlTag(htmlContent string) string { +func CleanHTMLTag(htmlContent string) string { if htmlContent == "" { return "" } @@ -41,7 +41,7 @@ func CleanHtmlTag(htmlContent string) string { var blankRegexp = regexp.MustCompile(`\s`) -func HtmlFormatWordCount(html string) int64 { - text := CleanHtmlTag(html) +func HTMLFormatWordCount(html string) int64 { + text := CleanHTMLTag(html) return int64(utf8.RuneCountInString(text) - len(blankRegexp.FindSubmatchIndex(StringToBytes(text)))) } diff --git a/util/conv.go b/util/conv.go index 9fc8887..8e4dc68 100644 --- a/util/conv.go +++ b/util/conv.go @@ -48,7 +48,7 @@ func Md5Hex(str string) string { } func MapKeyToArray[K comparable, V any](m map[K]V) []K { - var values []K + values := make([]K, 0, len(m)) for k := range m { values = append(values, k) diff --git a/util/file.go b/util/file.go index 05548d4..634b42e 100644 --- a/util/file.go +++ b/util/file.go @@ -18,14 +18,14 @@ func ZipFile(dst string, srcs ...string) (err error) { return xerr.NoType.Wrap(err).WithMsg("create zip file err") } defer func() { - if err := fw.Close(); err != nil { + if err = fw.Close(); err != nil { err = xerr.NoType.Wrap(err).WithMsg("close file") } }() // 通过 fw 来创建 zip.Write zw := zip.NewWriter(fw) defer func() { - if err := zw.Close(); err != nil { + if err = zw.Close(); err != nil { err = xerr.NoType.Wrap(err).WithMsg("close zip file") } }() @@ -69,10 +69,10 @@ func ZipFile(dst string, srcs ...string) (err error) { // 打开要压缩的文件 fr, err := os.Open(path) - defer fr.Close() if err != nil { return } + defer fr.Close() // 将打开的文件 Copy 到 w _, err = io.Copy(w, fr) @@ -91,16 +91,14 @@ func ZipFile(dst string, srcs ...string) (err error) { } func Unzip(src string, dest string) ([]string, error) { - var filenames []string - r, err := zip.OpenReader(src) if err != nil { - return filenames, err + return nil, err } defer r.Close() + filenames := make([]string, 0, len(r.File)) for _, f := range r.File { - // Store filename/path for returning and using later on fpath := filepath.Join(dest, f.Name) @@ -113,7 +111,10 @@ func Unzip(src string, dest string) ([]string, error) { if f.FileInfo().IsDir() { // Make Folder - os.MkdirAll(fpath, os.ModePerm) + err := os.MkdirAll(fpath, os.ModePerm) + if err != nil { + return nil, xerr.WithStatus(err, xerr.StatusInternalServerError) + } continue } @@ -148,10 +149,8 @@ func Unzip(src string, dest string) ([]string, error) { func CopyDir(srcPath, desPath string) error { if srcInfo, err := os.Stat(srcPath); err != nil { return err - } else { - if !srcInfo.IsDir() { - return xerr.WithMsg(nil, "src is not dir") - } + } else if !srcInfo.IsDir() { + return xerr.WithMsg(nil, "src is not dir") } if err := MakeDir(desPath); err != nil { @@ -159,10 +158,8 @@ func CopyDir(srcPath, desPath string) error { } if desInfo, err := os.Stat(desPath); err != nil { return err - } else { - if !desInfo.IsDir() { - return xerr.WithMsg(nil, "dest is not dir") - } + } else if !desInfo.IsDir() { + return xerr.WithMsg(nil, "dest is not dir") } if strings.TrimSpace(srcPath) == strings.TrimSpace(desPath) { @@ -178,14 +175,14 @@ func CopyDir(srcPath, desPath string) error { return nil } - destNewPath := strings.Replace(path, srcPath, desPath, -1) + destNewPath := strings.ReplaceAll(path, srcPath, desPath) if !f.IsDir() { - CopyFile(path, destNewPath) - } else { - if !FileIsExisted(destNewPath) { - return MakeDir(destNewPath) + if _, err = CopyFile(path, destNewPath); err != nil { + return err } + } else if !FileIsExisted(destNewPath) { + return MakeDir(destNewPath) } return nil diff --git a/util/haloerr/error.go b/util/haloerr/error.go index 2dff5ac..66de984 100644 --- a/util/haloerr/error.go +++ b/util/haloerr/error.go @@ -73,16 +73,17 @@ func (ce *customError) Format(s fmt.State, verb rune) { case 'v': if s.Flag('+') { fmt.Fprintf(s, "%+v\n", ce.Cause()) - io.WriteString(s, ce.msg) + _, _ = io.WriteString(s, ce.msg) return } fallthrough case 's', 'q': - io.WriteString(s, ce.Error()) + _, _ = io.WriteString(s, ce.Error()) } } func WithStatus(err error, status int) *customError { + //nolint:errorlint ee, ok := err.(*customError) if ok { return &customError{errorType: ee.errorType, cause: ee, httpStatus: status} @@ -91,6 +92,7 @@ func WithStatus(err error, status int) *customError { } func WithMsg(err error, msg string) *customError { + //nolint:errorlint ee, ok := err.(*customError) if ok { return &customError{errorType: ee.errorType, cause: ee, httpStatus: -1, msg: msg} @@ -99,6 +101,7 @@ func WithMsg(err error, msg string) *customError { } func WithErrMsgf(err error, errMsg string, args ...interface{}) *customError { + //nolint:errorlint ee, ok := err.(*customError) if ok { return &customError{errorType: ee.errorType, cause: err, httpStatus: -1, errMsg: fmt.Sprintf(errMsg, args...)} @@ -120,14 +123,16 @@ func (ce *customError) WithMsg(msg string) *customError { // GetType returns the error type func GetType(err error) ErrorType { + //nolint:errorlint if ee, ok := err.(*customError); ok { return ee.errorType } return NoType } -func GetHttpStatus(err error) int { +func GetHTTPStatus(err error) int { for err != nil { + //nolint:errorlint if e, ok := err.(*customError); ok { if e.httpStatus != -1 { return e.httpStatus @@ -143,6 +148,7 @@ func GetHttpStatus(err error) int { func GetMessage(err error) string { for err != nil { + //nolint:errorlint if e, ok := err.(*customError); ok { if e.msg != "" { return e.msg diff --git a/util/rainbow_page.go b/util/rainbow_page.go index a128835..c54ce9b 100644 --- a/util/rainbow_page.go +++ b/util/rainbow_page.go @@ -11,17 +11,20 @@ func RainbowPage(page, total, display int) []int { if total < display { length = total } + + //nolint:gosimple result := make([]int, length, length) if total >= display { - if page <= left { + switch { + case page <= left: for i := 0; i < length; i++ { result[i] = i + 1 } - } else if page > total-right { + case page > total-right: for i := 0; i < length; i++ { result[i] = i + total - display + 1 } - } else { + default: for i := 0; i < length; i++ { if isEven { result[i] = i + page - length + 1 diff --git a/util/xerr/error.go b/util/xerr/error.go index 2dff5ac..66de984 100644 --- a/util/xerr/error.go +++ b/util/xerr/error.go @@ -73,16 +73,17 @@ func (ce *customError) Format(s fmt.State, verb rune) { case 'v': if s.Flag('+') { fmt.Fprintf(s, "%+v\n", ce.Cause()) - io.WriteString(s, ce.msg) + _, _ = io.WriteString(s, ce.msg) return } fallthrough case 's', 'q': - io.WriteString(s, ce.Error()) + _, _ = io.WriteString(s, ce.Error()) } } func WithStatus(err error, status int) *customError { + //nolint:errorlint ee, ok := err.(*customError) if ok { return &customError{errorType: ee.errorType, cause: ee, httpStatus: status} @@ -91,6 +92,7 @@ func WithStatus(err error, status int) *customError { } func WithMsg(err error, msg string) *customError { + //nolint:errorlint ee, ok := err.(*customError) if ok { return &customError{errorType: ee.errorType, cause: ee, httpStatus: -1, msg: msg} @@ -99,6 +101,7 @@ func WithMsg(err error, msg string) *customError { } func WithErrMsgf(err error, errMsg string, args ...interface{}) *customError { + //nolint:errorlint ee, ok := err.(*customError) if ok { return &customError{errorType: ee.errorType, cause: err, httpStatus: -1, errMsg: fmt.Sprintf(errMsg, args...)} @@ -120,14 +123,16 @@ func (ce *customError) WithMsg(msg string) *customError { // GetType returns the error type func GetType(err error) ErrorType { + //nolint:errorlint if ee, ok := err.(*customError); ok { return ee.errorType } return NoType } -func GetHttpStatus(err error) int { +func GetHTTPStatus(err error) int { for err != nil { + //nolint:errorlint if e, ok := err.(*customError); ok { if e.httpStatus != -1 { return e.httpStatus @@ -143,6 +148,7 @@ func GetHttpStatus(err error) int { func GetMessage(err error) string { for err != nil { + //nolint:errorlint if e, ok := err.(*customError); ok { if e.msg != "" { return e.msg