This is an automated email from the ASF dual-hosted git repository. linkinstar pushed a commit to branch refactor/1.7.1/lint in repository https://gitbox.apache.org/repos/asf/answer.git
commit fc0b7db7244c6ccc52b6beeb1473a1b23f51b49b Author: LinkinStars <[email protected]> AuthorDate: Mon Dec 1 12:23:50 2025 +0800 refactor(lint): improve error handling and code consistency across multiple files --- .golangci.yaml | 13 +++++- cmd/wire.go | 3 +- internal/base/conf/conf.go | 4 +- internal/base/constant/ctx_flag.go | 7 +++ internal/base/data/data.go | 2 +- internal/base/handler/lang.go | 2 +- internal/base/handler/short_id.go | 2 +- internal/base/server/http_funcmap.go | 9 ++-- internal/base/validator/validator.go | 2 +- internal/cli/build.go | 52 ---------------------- internal/cli/config.go | 6 ++- internal/cli/dump.go | 4 +- internal/cli/install_check.go | 8 +++- internal/cli/reset_password.go | 4 +- internal/controller/template_controller.go | 43 +++++++----------- internal/controller/template_render/controller.go | 1 - internal/controller/user_controller.go | 7 +-- internal/install/install_from_env.go | 3 +- internal/migrations/migrations.go | 4 +- internal/migrations/v22.go | 3 ++ internal/migrations/v24.go | 3 -- internal/repo/answer/answer_repo.go | 1 + .../repo/plugin_config/plugin_user_config_repo.go | 2 +- internal/repo/repo_test/repo_main_test.go | 2 +- internal/repo/tag/tag_rel_repo.go | 1 + internal/service/action/captcha_service.go | 7 ++- internal/service/action/captcha_strategy.go | 27 +++++------ internal/service/badge/badge_event_handler.go | 1 - internal/service/badge/badge_service.go | 26 ++++------- internal/service/content/question_service.go | 22 +++++---- internal/service/content/revision_service.go | 5 +-- internal/service/content/search_service.go | 3 ++ internal/service/content/vote_service.go | 3 -- internal/service/dashboard/dashboard_service.go | 8 ++-- .../service/file_record/file_record_service.go | 1 - internal/service/importer/importer_service.go | 5 +-- internal/service/meta/meta_service.go | 12 ++--- .../notification/invite_answer_notification.go | 2 +- .../notification/new_answer_notification.go | 2 +- .../notification/new_comment_notification.go | 2 +- .../notification/new_question_notification.go | 2 +- .../service/notification/notification_service.go | 4 +- .../service/notification_common/notification.go | 3 ++ internal/service/report_handle/report_handle.go | 6 +++ internal/service/review/review_service.go | 1 - internal/service/siteinfo/siteinfo_service.go | 4 +- internal/service/uploader/upload.go | 28 ++++++++---- internal/service/user_admin/user_backyard.go | 11 ++--- .../user_notification_config_service.go | 8 ++-- pkg/checker/file_type.go | 4 +- pkg/checker/password.go | 3 +- pkg/converter/markdown.go | 7 ++- pkg/htmltext/htmltext.go | 4 +- plugin/kv_storage.go | 6 +-- plugin/plugin_test/plugin_main_test.go | 2 +- ui/static.go | 1 - 56 files changed, 194 insertions(+), 214 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index 263f63f7..611b49bc 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -17,7 +17,18 @@ version: "2" linters: - default: none + exclusions: + paths: + - answer-data + - ui + - i18n + enable: + - asasalint # checks for pass []any as any in variadic func(...any) + - asciicheck # checks that your code does not contain non-ASCII identifiers + - bidichk # checks for dangerous unicode character sequences + - bodyclose # checks whether HTTP response body is closed successfully + - canonicalheader # checks whether net/http.Header uses canonical header + - copyloopvar # detects places where loop variables are copied (Go 1.22+) formatters: enable: diff --git a/cmd/wire.go b/cmd/wire.go index b25026e5..3979ecbf 100644 --- a/cmd/wire.go +++ b/cmd/wire.go @@ -1,5 +1,4 @@ //go:build wireinject -// +build wireinject /* * Licensed to the Apache Software Foundation (ASF) under one @@ -32,7 +31,7 @@ import ( "github.com/apache/answer/internal/base/server" "github.com/apache/answer/internal/base/translator" "github.com/apache/answer/internal/controller" - "github.com/apache/answer/internal/controller/template_render" + templaterender "github.com/apache/answer/internal/controller/template_render" "github.com/apache/answer/internal/controller_admin" "github.com/apache/answer/internal/repo" "github.com/apache/answer/internal/router" diff --git a/internal/base/conf/conf.go b/internal/base/conf/conf.go index db83862b..04e3a19b 100644 --- a/internal/base/conf/conf.go +++ b/internal/base/conf/conf.go @@ -117,7 +117,9 @@ func ReadConfig(configFilePath string) (c *AllConfig, err error) { func RewriteConfig(configFilePath string, allConfig *AllConfig) error { buf := bytes.Buffer{} enc := yaml.NewEncoder(&buf) - defer enc.Close() + defer func() { + _ = enc.Close() + }() enc.SetIndent(2) if err := enc.Encode(allConfig); err != nil { return err diff --git a/internal/base/constant/ctx_flag.go b/internal/base/constant/ctx_flag.go index 2a757fa8..450491bb 100644 --- a/internal/base/constant/ctx_flag.go +++ b/internal/base/constant/ctx_flag.go @@ -23,3 +23,10 @@ const ( AcceptLanguageFlag = "Accept-Language" ShortIDFlag = "Short-ID-Enabled" ) + +type ContextKey string + +const ( + AcceptLanguageContextKey ContextKey = ContextKey(AcceptLanguageFlag) + ShortIDContextKey ContextKey = ContextKey(ShortIDFlag) +) diff --git a/internal/base/data/data.go b/internal/base/data/data.go index 1d24d718..7696d8f5 100644 --- a/internal/base/data/data.go +++ b/internal/base/data/data.go @@ -47,7 +47,7 @@ type Data struct { func NewData(db *xorm.Engine, cache cache.Cache) (*Data, func(), error) { cleanup := func() { log.Info("closing the data resources") - db.Close() + _ = db.Close() } return &Data{DB: db, Cache: cache}, cleanup, nil } diff --git a/internal/base/handler/lang.go b/internal/base/handler/lang.go index a676e5bc..4ff1ac7f 100644 --- a/internal/base/handler/lang.go +++ b/internal/base/handler/lang.go @@ -38,7 +38,7 @@ func GetLang(ctx *gin.Context) i18n.Language { // GetLangByCtx get language from header func GetLangByCtx(ctx context.Context) i18n.Language { - acceptLanguage, ok := ctx.Value(constant.AcceptLanguageFlag).(i18n.Language) + acceptLanguage, ok := ctx.Value(constant.AcceptLanguageContextKey).(i18n.Language) if ok { return acceptLanguage } diff --git a/internal/base/handler/short_id.go b/internal/base/handler/short_id.go index c763bf94..8f9a2a7e 100644 --- a/internal/base/handler/short_id.go +++ b/internal/base/handler/short_id.go @@ -27,7 +27,7 @@ import ( // GetEnableShortID get language from header func GetEnableShortID(ctx context.Context) bool { - flag, ok := ctx.Value(constant.ShortIDFlag).(bool) + flag, ok := ctx.Value(constant.ShortIDContextKey).(bool) if ok { return flag } diff --git a/internal/base/server/http_funcmap.go b/internal/base/server/http_funcmap.go index 8f6cac5f..db460457 100644 --- a/internal/base/server/http_funcmap.go +++ b/internal/base/server/http_funcmap.go @@ -21,7 +21,6 @@ package server import ( "html/template" - "math" "regexp" "strconv" "strings" @@ -107,15 +106,15 @@ var funcMap = template.FuncMap{ } if between >= 60 && between < 3600 { - min := math.Floor(float64(between / 60)) + min := between / 60 trans = translator.GlobalTrans.Tr(la, "ui.dates.x_minutes_ago") - return strings.ReplaceAll(trans, "{{count}}", strconv.FormatFloat(min, 'f', 0, 64)) + return strings.ReplaceAll(trans, "{{count}}", strconv.FormatInt(min, 10)) } if between >= 3600 && between < 3600*24 { - h := math.Floor(float64(between / 3600)) + h := between / 3600 trans = translator.GlobalTrans.Tr(la, "ui.dates.x_hours_ago") - return strings.ReplaceAll(trans, "{{count}}", strconv.FormatFloat(h, 'f', 0, 64)) + return strings.ReplaceAll(trans, "{{count}}", strconv.FormatInt(h, 10)) } if between >= 3600*24 && diff --git a/internal/base/validator/validator.go b/internal/base/validator/validator.go index 22761c52..9c7f6ec4 100644 --- a/internal/base/validator/validator.go +++ b/internal/base/validator/validator.go @@ -142,7 +142,7 @@ func Sanitizer(fl validator.FieldLevel) (res bool) { switch field.Kind() { case reflect.String: filter := bluemonday.UGCPolicy() - content := strings.Replace(filter.Sanitize(field.String()), "&", "&", -1) + content := strings.ReplaceAll(filter.Sanitize(field.String()), "&", "&") field.SetString(content) return true case reflect.Chan, reflect.Map, reflect.Slice, reflect.Array: diff --git a/internal/cli/build.go b/internal/cli/build.go index a5a4d938..efc876e3 100644 --- a/internal/cli/build.go +++ b/internal/cli/build.go @@ -34,7 +34,6 @@ import ( "github.com/Masterminds/semver/v3" "github.com/apache/answer/pkg/dir" "github.com/apache/answer/pkg/writer" - "github.com/apache/answer/ui" "github.com/segmentfault/pacman/log" "gopkg.in/yaml.v3" ) @@ -300,50 +299,6 @@ func copyUIFiles(b *buildingMaterial) (err error) { return nil } -// overwriteIndexTs overwrites index.ts file in ui/src/plugins/ dir -func overwriteIndexTs(b *buildingMaterial) (err error) { - localUIPluginDir := filepath.Join(b.tmpDir, "vendor/github.com/apache/answer/ui/src/plugins/") - - folders, err := getFolders(localUIPluginDir) - if err != nil { - return fmt.Errorf("failed to get folders: %w", err) - } - - content := generateIndexTsContent(folders) - err = os.WriteFile(filepath.Join(localUIPluginDir, "index.ts"), []byte(content), 0644) - if err != nil { - return fmt.Errorf("failed to write index.ts: %w", err) - } - return nil -} - -func getFolders(dir string) ([]string, error) { - var folders []string - files, err := os.ReadDir(dir) - if err != nil { - return nil, err - } - for _, file := range files { - if file.IsDir() && file.Name() != "builtin" { - folders = append(folders, file.Name()) - } - } - return folders, nil -} - -func generateIndexTsContent(folders []string) string { - builder := &strings.Builder{} - builder.WriteString("export default null;\n") - // Line 2:1: Delete `⏎` prettier/prettier - if len(folders) > 0 { - builder.WriteString("\n") - } - for _, folder := range folders { - builder.WriteString(fmt.Sprintf("export { default as %s } from '%s';\n", folder, folder)) - } - return builder.String() -} - // buildUI run pnpm install and pnpm build commands to build ui func buildUI(b *buildingMaterial) (err error) { localUIBuildDir := filepath.Join(b.tmpDir, "vendor/github.com/apache/answer/ui") @@ -362,13 +317,6 @@ func buildUI(b *buildingMaterial) (err error) { return nil } -func replaceNecessaryFile(b *buildingMaterial) (err error) { - fmt.Printf("try to replace ui build directory\n") - uiBuildDir := filepath.Join(b.tmpDir, "vendor/github.com/apache/answer/ui") - err = copyDirEntries(ui.Build, ".", uiBuildDir) - return err -} - // mergeI18nFiles merge i18n files func mergeI18nFiles(b *buildingMaterial) (err error) { fmt.Printf("try to merge i18n files\n") diff --git a/internal/cli/config.go b/internal/cli/config.go index ecb62a13..e2445c59 100644 --- a/internal/cli/config.go +++ b/internal/cli/config.go @@ -42,7 +42,9 @@ func SetDefaultConfig(dbConf *data.Database, cacheConf *data.CacheConf, field *C if err != nil { return err } - defer db.Close() + defer func() { + _ = db.Close() + }() cache, cacheCleanup, err := data.NewCache(cacheConf) if err != nil { @@ -50,7 +52,7 @@ func SetDefaultConfig(dbConf *data.Database, cacheConf *data.CacheConf, field *C } defer func() { if cache != nil { - cache.Flush(context.Background()) + _ = cache.Flush(context.Background()) cacheCleanup() } }() diff --git a/internal/cli/dump.go b/internal/cli/dump.go index e5d52821..e63ef1a9 100644 --- a/internal/cli/dump.go +++ b/internal/cli/dump.go @@ -34,7 +34,9 @@ func DumpAllData(dataConf *data.Database, dumpDataPath string) error { if err != nil { return err } - defer db.Close() + defer func() { + _ = db.Close() + }() if err = db.Ping(); err != nil { return err } diff --git a/internal/cli/install_check.go b/internal/cli/install_check.go index 9326e069..c3fadcab 100644 --- a/internal/cli/install_check.go +++ b/internal/cli/install_check.go @@ -43,7 +43,9 @@ func CheckDBConnection(dataConf *data.Database) bool { fmt.Printf("connection database failed: %s\n", err) return false } - defer db.Close() + defer func() { + _ = db.Close() + }() if err = db.Ping(); err != nil { fmt.Printf("connection ping database failed: %s\n", err) return false @@ -59,7 +61,9 @@ func CheckDBTableExist(dataConf *data.Database) bool { fmt.Printf("connection database failed: %s\n", err) return false } - defer db.Close() + defer func() { + _ = db.Close() + }() if err = db.Ping(); err != nil { fmt.Printf("connection ping database failed: %s\n", err) return false diff --git a/internal/cli/reset_password.go b/internal/cli/reset_password.go index 2a7d1af4..dbb3422a 100644 --- a/internal/cli/reset_password.go +++ b/internal/cli/reset_password.go @@ -77,7 +77,9 @@ func ResetPassword(ctx context.Context, dataDirPath string, opts *ResetPasswordO if err != nil { return fmt.Errorf("connect database failed: %w", err) } - defer db.Close() + defer func() { + _ = db.Close() + }() cache, cacheCleanup, err := data.NewCache(config.Data.Cache) if err != nil { diff --git a/internal/controller/template_controller.go b/internal/controller/template_controller.go index 83cd58c3..801e129c 100644 --- a/internal/controller/template_controller.go +++ b/internal/controller/template_controller.go @@ -162,11 +162,9 @@ func (tc *TemplateController) Index(ctx *gin.Context) { siteInfo := tc.SiteInfo(ctx) siteInfo.Canonical = siteInfo.General.SiteUrl - UrlUseTitle := false - if siteInfo.SiteSeo.Permalink == constant.PermalinkQuestionIDAndTitle || - siteInfo.SiteSeo.Permalink == constant.PermalinkQuestionIDAndTitleByShortID { - UrlUseTitle = true - } + UrlUseTitle := siteInfo.SiteSeo.Permalink == constant.PermalinkQuestionIDAndTitle || + siteInfo.SiteSeo.Permalink == constant.PermalinkQuestionIDAndTitleByShortID + siteInfo.Title = "" tc.html(ctx, http.StatusOK, "question.html", siteInfo, gin.H{ "data": data, @@ -205,11 +203,9 @@ func (tc *TemplateController) QuestionList(ctx *gin.Context) { siteInfo.Canonical = fmt.Sprintf("%s/questions?page=%d", siteInfo.General.SiteUrl, page) } - UrlUseTitle := false - if siteInfo.SiteSeo.Permalink == constant.PermalinkQuestionIDAndTitle || - siteInfo.SiteSeo.Permalink == constant.PermalinkQuestionIDAndTitleByShortID { - UrlUseTitle = true - } + UrlUseTitle := siteInfo.SiteSeo.Permalink == constant.PermalinkQuestionIDAndTitle || + siteInfo.SiteSeo.Permalink == constant.PermalinkQuestionIDAndTitleByShortID + siteInfo.Title = fmt.Sprintf("%s - %s", translator.Tr(handler.GetLang(ctx), constant.QuestionsTitleTrKey), siteInfo.General.Name) tc.html(ctx, http.StatusOK, "question.html", siteInfo, gin.H{ "data": data, @@ -371,11 +367,8 @@ func (tc *TemplateController) QuestionInfo(ctx *gin.Context) { return } - UrlUseTitle := false - if siteInfo.SiteSeo.Permalink == constant.PermalinkQuestionIDAndTitle || - siteInfo.SiteSeo.Permalink == constant.PermalinkQuestionIDAndTitleByShortID { - UrlUseTitle = true - } + UrlUseTitle := siteInfo.SiteSeo.Permalink == constant.PermalinkQuestionIDAndTitle || + siteInfo.SiteSeo.Permalink == constant.PermalinkQuestionIDAndTitleByShortID //related question userID := middleware.GetLoginUserIDFromContext(ctx) @@ -434,7 +427,7 @@ func (tc *TemplateController) QuestionInfo(ctx *gin.Context) { for _, tag := range detail.Tags { tags = append(tags, tag.DisplayName) } - siteInfo.Keywords = strings.Replace(strings.Trim(fmt.Sprint(tags), "[]"), " ", ",", -1) + siteInfo.Keywords = strings.ReplaceAll(strings.Trim(fmt.Sprint(tags), "[]"), " ", ",") siteInfo.Title = fmt.Sprintf("%s - %s", detail.Title, siteInfo.General.Name) tc.html(ctx, http.StatusOK, "question-detail.html", siteInfo, gin.H{ "id": id, @@ -504,11 +497,9 @@ func (tc *TemplateController) TagInfo(ctx *gin.Context) { } siteInfo.Keywords = tagInfo.DisplayName - UrlUseTitle := false - if siteInfo.SiteSeo.Permalink == constant.PermalinkQuestionIDAndTitle || - siteInfo.SiteSeo.Permalink == constant.PermalinkQuestionIDAndTitleByShortID { - UrlUseTitle = true - } + UrlUseTitle := siteInfo.SiteSeo.Permalink == constant.PermalinkQuestionIDAndTitle || + siteInfo.SiteSeo.Permalink == constant.PermalinkQuestionIDAndTitleByShortID + siteInfo.Title = fmt.Sprintf("'%s' %s - %s", tagInfo.DisplayName, translator.Tr(handler.GetLang(ctx), constant.QuestionsTitleTrKey), siteInfo.General.Name) tc.html(ctx, http.StatusOK, "tag-detail.html", siteInfo, gin.H{ "tag": tagInfo, @@ -570,11 +561,9 @@ func (tc *TemplateController) Page404(ctx *gin.Context) { } func (tc *TemplateController) html(ctx *gin.Context, code int, tpl string, siteInfo *schema.TemplateSiteInfoResp, data gin.H) { - var ( - prefix = "" - cssPath = "" - scriptPath = make([]string, len(tc.scriptPath)) - ) + prefix := "" + cssPath := "" + scriptPath := make([]string, len(tc.scriptPath)) _ = plugin.CallCDN(func(fn plugin.CDN) error { prefix = fn.GetStaticPrefix() @@ -612,7 +601,7 @@ func (tc *TemplateController) html(ctx *gin.Context, code int, tpl string, siteI data["description"] = siteInfo.Description data["language"] = handler.GetLang(ctx) data["timezone"] = siteInfo.Interface.TimeZone - language := strings.Replace(siteInfo.Interface.Language, "_", "-", -1) + language := strings.ReplaceAll(siteInfo.Interface.Language, "_", "-") data["lang"] = language data["HeadCode"] = siteInfo.CustomCssHtml.CustomHead data["HeaderCode"] = siteInfo.CustomCssHtml.CustomHeader diff --git a/internal/controller/template_render/controller.go b/internal/controller/template_render/controller.go index 5f802fa7..3412010d 100644 --- a/internal/controller/template_render/controller.go +++ b/internal/controller/template_render/controller.go @@ -101,7 +101,6 @@ func Paginator(page, pageSize int, nums int64) *schema.Paginator { case page >= 3 && totalpages > 5: start := page - 3 + 1 pages = make([]int, 5) - prevpage = page - 3 for i := range pages { pages[i] = start + i } diff --git a/internal/controller/user_controller.go b/internal/controller/user_controller.go index 49b9b23c..e4a3b3d3 100644 --- a/internal/controller/user_controller.go +++ b/internal/controller/user_controller.go @@ -151,7 +151,7 @@ func (uc *UserController) UserEmailLogin(ctx *gin.Context) { resp, err := uc.userService.EmailLogin(ctx, req) if err != nil { - _, _ = uc.actionService.ActionRecordAdd(ctx, entity.CaptchaActionPassword, ctx.ClientIP()) + uc.actionService.ActionRecordAdd(ctx, entity.CaptchaActionPassword, ctx.ClientIP()) errFields := append([]*validator.FormErrorField{}, &validator.FormErrorField{ ErrorField: "e_mail", ErrorMsg: translator.Tr(handler.GetLang(ctx), reason.EmailOrPasswordWrong), @@ -404,10 +404,7 @@ func (uc *UserController) UserModifyPassWord(ctx *gin.Context) { handler.HandleResponse(ctx, errors.BadRequest(reason.CaptchaVerificationFailed), errFields) return } - _, err := uc.actionService.ActionRecordAdd(ctx, entity.CaptchaActionEditUserinfo, req.UserID) - if err != nil { - log.Error(err) - } + uc.actionService.ActionRecordAdd(ctx, entity.CaptchaActionEditUserinfo, req.UserID) } oldPassVerification, err := uc.userService.UserModifyPassWordVerification(ctx, req) diff --git a/internal/install/install_from_env.go b/internal/install/install_from_env.go index c05d2aab..02bc7638 100644 --- a/internal/install/install_from_env.go +++ b/internal/install/install_from_env.go @@ -22,6 +22,7 @@ package install import ( "bytes" "encoding/json" + "errors" "fmt" "net/http" "net/http/httptest" @@ -143,7 +144,7 @@ func requestAPI(req any, method, url string, handlerFunc gin.HandlerFunc) error } handlerFunc(c) if w.Code != http.StatusOK { - return fmt.Errorf(gjson.Get(w.Body.String(), "msg").String()) + return errors.New(gjson.Get(w.Body.String(), "msg").String()) } return nil } diff --git a/internal/migrations/migrations.go b/internal/migrations/migrations.go index 9caa28ed..2fbfbb7f 100644 --- a/internal/migrations/migrations.go +++ b/internal/migrations/migrations.go @@ -147,7 +147,9 @@ func Migrate(debug bool, dbConf *data.Database, cacheConf *data.CacheConf, upgra fmt.Println("new database failed: ", err.Error()) return err } - defer engine.Close() + defer func() { + _ = engine.Close() + }() currentDBVersion, err := GetCurrentDBVersion(engine) if err != nil { diff --git a/internal/migrations/v22.go b/internal/migrations/v22.go index e7177dea..5367f5d4 100644 --- a/internal/migrations/v22.go +++ b/internal/migrations/v22.go @@ -61,6 +61,9 @@ func addBadges(ctx context.Context, x *xorm.Engine) (err error) { if exist { badge.ID = beans.ID _, err = x.Context(ctx).ID(beans.ID).Update(badge) + if err != nil { + return fmt.Errorf("update badge failed: %w", err) + } continue } badge.ID, err = uniqueIDRepo.GenUniqueIDStr(ctx, new(entity.Badge).TableName()) diff --git a/internal/migrations/v24.go b/internal/migrations/v24.go index a488679f..86d62425 100644 --- a/internal/migrations/v24.go +++ b/internal/migrations/v24.go @@ -66,8 +66,5 @@ func addQuestionLinkedCount(ctx context.Context, x *xorm.Engine) error { } } - type Question struct { - LinkedCount int `xorm:"not null default 0 INT(11) linked_count"` - } return x.Context(ctx).Sync(new(entity.Question)) } diff --git a/internal/repo/answer/answer_repo.go b/internal/repo/answer/answer_repo.go index c5447bef..0f1ae814 100644 --- a/internal/repo/answer/answer_repo.go +++ b/internal/repo/answer/answer_repo.go @@ -503,6 +503,7 @@ func (ar *answerRepo) updateSearch(ctx context.Context, answerID string) (err er err = st.Find(&tagListList) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() + return } for _, tag := range tagListList { tags = append(tags, tag.TagID) diff --git a/internal/repo/plugin_config/plugin_user_config_repo.go b/internal/repo/plugin_config/plugin_user_config_repo.go index d14442a5..df5ae29b 100644 --- a/internal/repo/plugin_config/plugin_user_config_repo.go +++ b/internal/repo/plugin_config/plugin_user_config_repo.go @@ -71,7 +71,7 @@ func (ur *pluginUserConfigRepo) SaveUserPluginConfig(ctx context.Context, userID return nil, nil }) if err != nil { - err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() + return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } return nil } diff --git a/internal/repo/repo_test/repo_main_test.go b/internal/repo/repo_test/repo_main_test.go index a59ae626..919ca94e 100644 --- a/internal/repo/repo_test/repo_main_test.go +++ b/internal/repo/repo_test/repo_main_test.go @@ -77,7 +77,7 @@ func TestMain(t *testing.M) { dbSetting = dbSettingMapping[string(schemas.SQLITE)] } if dbSetting.Driver == string(schemas.SQLITE) { - os.RemoveAll(dbSetting.Connection) + _ = os.RemoveAll(dbSetting.Connection) } defer func() { diff --git a/internal/repo/tag/tag_rel_repo.go b/internal/repo/tag/tag_rel_repo.go index 3634c97a..a52b1bf5 100644 --- a/internal/repo/tag/tag_rel_repo.go +++ b/internal/repo/tag/tag_rel_repo.go @@ -198,6 +198,7 @@ func (tr *tagRelRepo) GetTagRelDefaultStatusByObjectID(ctx context.Context, obje exist, err := tr.data.DB.Context(ctx).ID(objectID).Cols("show", "status").Get(&question) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() + return } if exist && (question.Show == entity.QuestionHide || question.Status == entity.QuestionStatusDeleted) { return entity.TagRelStatusHide, nil diff --git a/internal/service/action/captcha_service.go b/internal/service/action/captcha_service.go index 04f8b16a..aefb7051 100644 --- a/internal/service/action/captcha_service.go +++ b/internal/service/action/captcha_service.go @@ -106,11 +106,11 @@ func (cs *CaptchaService) ActionRecordVerifyCaptcha( return pass } -func (cs *CaptchaService) ActionRecordAdd(ctx context.Context, actionType string, unit string) (int, error) { +func (cs *CaptchaService) ActionRecordAdd(ctx context.Context, actionType string, unit string) { info, err := cs.captchaRepo.GetActionType(ctx, unit, actionType) if err != nil { log.Error(err) - return 0, err + return } amount := 1 if info != nil { @@ -118,9 +118,8 @@ func (cs *CaptchaService) ActionRecordAdd(ctx context.Context, actionType string } err = cs.captchaRepo.SetActionType(ctx, unit, actionType, "", amount) if err != nil { - return 0, err + log.Error(err) } - return amount, nil } func (cs *CaptchaService) ActionRecordDel(ctx context.Context, actionType string, unit string) { diff --git a/internal/service/action/captcha_strategy.go b/internal/service/action/captcha_strategy.go index 3befda82..b423b583 100644 --- a/internal/service/action/captcha_strategy.go +++ b/internal/service/action/captcha_strategy.go @@ -89,7 +89,9 @@ func (cs *CaptchaService) CaptchaActionPassword(ctx context.Context, unit string return false } if now-actionInfo.LastTime != 0 && now-actionInfo.LastTime > setTime { - cs.captchaRepo.SetActionType(ctx, unit, entity.CaptchaActionPassword, "", 0) + if err := cs.captchaRepo.SetActionType(ctx, unit, entity.CaptchaActionPassword, "", 0); err != nil { + log.Error(err) + } } return true } @@ -105,7 +107,9 @@ func (cs *CaptchaService) CaptchaActionEditUserinfo(ctx context.Context, unit st return false } if now-actionInfo.LastTime != 0 && now-actionInfo.LastTime > setTime { - cs.captchaRepo.SetActionType(ctx, unit, entity.CaptchaActionEditUserinfo, "", 0) + if err := cs.captchaRepo.SetActionType(ctx, unit, entity.CaptchaActionEditUserinfo, "", 0); err != nil { + log.Error(err) + } } return true } @@ -154,10 +158,7 @@ func (cs *CaptchaService) CaptchaActionEdit(ctx context.Context, unit string, ac return true } setNum := 10 - if actionInfo.Num >= setNum { - return false - } - return true + return actionInfo.Num < setNum } func (cs *CaptchaService) CaptchaActionInvitationAnswer(ctx context.Context, unit string, actionInfo *entity.ActionRecordInfo) bool { @@ -165,10 +166,7 @@ func (cs *CaptchaService) CaptchaActionInvitationAnswer(ctx context.Context, uni return true } setNum := 30 - if actionInfo.Num >= setNum { - return false - } - return true + return actionInfo.Num < setNum } func (cs *CaptchaService) CaptchaActionSearch(ctx context.Context, unit string, actionInfo *entity.ActionRecordInfo) bool { @@ -182,7 +180,9 @@ func (cs *CaptchaService) CaptchaActionSearch(ctx context.Context, unit string, return false } if now-actionInfo.LastTime > setTime { - cs.captchaRepo.SetActionType(ctx, unit, entity.CaptchaActionSearch, "", 0) + if err := cs.captchaRepo.SetActionType(ctx, unit, entity.CaptchaActionSearch, "", 0); err != nil { + log.Error(err) + } } return true } @@ -218,8 +218,5 @@ func (cs *CaptchaService) CaptchaActionVote(ctx context.Context, unit string, ac return true } setNum := 40 - if actionInfo.Num >= setNum { - return false - } - return true + return actionInfo.Num < setNum } diff --git a/internal/service/badge/badge_event_handler.go b/internal/service/badge/badge_event_handler.go index cc161f6a..24cabf29 100644 --- a/internal/service/badge/badge_event_handler.go +++ b/internal/service/badge/badge_event_handler.go @@ -32,7 +32,6 @@ import ( type BadgeEventService struct { data *data.Data eventQueueService event_queue.EventQueueService - badgeAwardRepo BadgeAwardRepo badgeRepo BadgeRepo eventRuleRepo EventRuleRepo badgeAwardService *BadgeAwardService diff --git a/internal/service/badge/badge_service.go b/internal/service/badge/badge_service.go index 03b8a877..ebb90450 100644 --- a/internal/service/badge/badge_service.go +++ b/internal/service/badge/badge_service.go @@ -206,10 +206,8 @@ func (b *BadgeService) ListPaged(ctx context.Context, req *schema.GetBadgeListPa resp = make([]*schema.GetBadgeListPagedResp, len(badges)) general, siteErr := b.siteInfoCommonService.GetSiteGeneral(ctx) - var baseURL = "" - if siteErr != nil { - baseURL = "" - } else { + baseURL := "" + if siteErr == nil { baseURL = general.SiteUrl } @@ -246,31 +244,23 @@ func (b *BadgeService) searchByName(ctx context.Context, name string) (result [] // GetBadgeInfo get badge info func (b *BadgeService) GetBadgeInfo(ctx *gin.Context, id string, userID string) (info *schema.GetBadgeInfoResp, err error) { - var ( - badge *entity.Badge - earnedTotal int64 = 0 - exists = false - ) - - badge, exists, err = b.badgeRepo.GetByID(ctx, id) + badge, exists, err := b.badgeRepo.GetByID(ctx, id) if err != nil { - return + return nil, err } if !exists || badge.Status == entity.BadgeStatusInactive { - err = errors.BadRequest(reason.BadgeObjectNotFound) - return + return nil, errors.BadRequest(reason.BadgeObjectNotFound) } + var earnedTotal int64 if len(userID) > 0 { earnedTotal = b.badgeAwardRepo.CountByUserIdAndBadgeId(ctx, userID, badge.ID) } + baseURL := "" general, siteErr := b.siteInfoCommonService.GetSiteGeneral(ctx) - var baseURL = "" - if siteErr != nil { - baseURL = "" - } else { + if siteErr == nil { baseURL = general.SiteUrl } diff --git a/internal/service/content/question_service.go b/internal/service/content/question_service.go index 1d1d1af3..da15fae5 100644 --- a/internal/service/content/question_service.go +++ b/internal/service/content/question_service.go @@ -277,7 +277,7 @@ func (qs *QuestionService) CheckAddQuestion(ctx context.Context, req *schema.Que if tagerr != nil { return errorlist, tagerr } - if !req.QuestionPermission.CanUseReservedTag { + if !req.CanUseReservedTag { taglist, err := qs.AddQuestionCheckTags(ctx, Tags) errMsg := fmt.Sprintf(`"%s" can only be used by moderators.`, strings.Join(taglist, ",")) @@ -350,7 +350,7 @@ func (qs *QuestionService) AddQuestion(ctx context.Context, req *schema.Question if tagerr != nil { return questionInfo, tagerr } - if !req.QuestionPermission.CanUseReservedTag { + if !req.CanUseReservedTag { taglist, err := qs.AddQuestionCheckTags(ctx, tags) errMsg := fmt.Sprintf(`"%s" can only be used by moderators.`, strings.Join(taglist, ",")) @@ -1397,13 +1397,17 @@ func (qs *QuestionService) GetQuestionsByTitle(ctx context.Context, title string for _, question := range res { questionIDs = append(questionIDs, question.ID) } - questions, err = qs.questionRepo.FindByID(ctx, questionIDs) + var questionErr error + questions, questionErr = qs.questionRepo.FindByID(ctx, questionIDs) + if questionErr != nil { + return resp, questionErr + } } else { - questions, err = qs.questionRepo.GetQuestionsByTitle(ctx, title, 10) - } - - if err != nil { - return resp, err + var questionErr error + questions, questionErr = qs.questionRepo.GetQuestionsByTitle(ctx, title, 10) + if questionErr != nil { + return resp, questionErr + } } for _, question := range questions { item := &schema.QuestionBaseInfo{} @@ -1723,7 +1727,7 @@ func (qs *QuestionService) SitemapCron(ctx context.Context) { log.Error(err) return } - ctx = context.WithValue(ctx, constant.ShortIDFlag, siteSeo.IsShortLink()) + ctx = context.WithValue(ctx, constant.ShortIDContextKey, siteSeo.IsShortLink()) qs.questioncommon.SitemapCron(ctx) } diff --git a/internal/service/content/revision_service.go b/internal/service/content/revision_service.go index 1aed4cf8..a5cefeb4 100644 --- a/internal/service/content/revision_service.go +++ b/internal/service/content/revision_service.go @@ -41,7 +41,6 @@ import ( "github.com/apache/answer/internal/service/review" "github.com/apache/answer/internal/service/revision" "github.com/apache/answer/internal/service/tag_common" - tagcommon "github.com/apache/answer/internal/service/tag_common" usercommon "github.com/apache/answer/internal/service/user_common" "github.com/apache/answer/pkg/converter" "github.com/apache/answer/pkg/htmltext" @@ -62,7 +61,7 @@ type RevisionService struct { questionRepo questioncommon.QuestionRepo answerRepo answercommon.AnswerRepo tagRepo tag_common.TagRepo - tagCommon *tagcommon.TagCommonService + tagCommon *tag_common.TagCommonService notificationQueueService notice_queue.NotificationQueueService activityQueueService activity_queue.ActivityQueueService reportRepo report_common.ReportRepo @@ -79,7 +78,7 @@ func NewRevisionService( questionRepo questioncommon.QuestionRepo, answerRepo answercommon.AnswerRepo, tagRepo tag_common.TagRepo, - tagCommon *tagcommon.TagCommonService, + tagCommon *tag_common.TagCommonService, notificationQueueService notice_queue.NotificationQueueService, activityQueueService activity_queue.ActivityQueueService, reportRepo report_common.ReportRepo, diff --git a/internal/service/content/search_service.go b/internal/service/content/search_service.go index 98add093..ccafcd82 100644 --- a/internal/service/content/search_service.go +++ b/internal/service/content/search_service.go @@ -93,6 +93,9 @@ func (ss *SearchService) searchByPlugin(ctx context.Context, finder plugin.Searc } else if cond.SearchAnswer() { res, resp.Total, err = finder.SearchAnswers(ctx, cond.Convert2PluginSearchCond(dto.Page, dto.Size, dto.Order)) } + if err != nil { + return resp, err + } resp.SearchResults, err = ss.searchRepo.ParseSearchPluginResult(ctx, res, cond.Words) return resp, err diff --git a/internal/service/content/vote_service.go b/internal/service/content/vote_service.go index 92f0c996..aa615049 100644 --- a/internal/service/content/vote_service.go +++ b/internal/service/content/vote_service.go @@ -26,8 +26,6 @@ import ( "github.com/apache/answer/internal/service/event_queue" - "github.com/apache/answer/internal/service/activity_common" - "github.com/apache/answer/internal/base/constant" "github.com/apache/answer/internal/base/handler" "github.com/apache/answer/internal/base/pager" @@ -64,7 +62,6 @@ type VoteService struct { answerRepo answercommon.AnswerRepo commentCommonRepo comment_common.CommentCommonRepo objectService *object_info.ObjService - activityRepo activity_common.ActivityRepo eventQueueService event_queue.EventQueueService } diff --git a/internal/service/dashboard/dashboard_service.go b/internal/service/dashboard/dashboard_service.go index d9198e6d..91f0e338 100644 --- a/internal/service/dashboard/dashboard_service.go +++ b/internal/service/dashboard/dashboard_service.go @@ -274,7 +274,9 @@ func (ds *dashboardService) remoteVersion(ctx context.Context) string { log.Errorf("request remote version failed: %s", err) return "" } - defer resp.Body.Close() + defer func() { + _ = resp.Body.Close() + }() respByte, err := io.ReadAll(resp.Body) if err != nil { @@ -358,7 +360,7 @@ func (ds *dashboardService) GetDatabaseSize() (dbSize string) { if err != nil { log.Warnf("get db size failed: %s", err) } else { - if res != nil && len(res) > 0 && res[0]["db_size"] != nil { + if len(res) > 0 && res[0]["db_size"] != nil { dbSizeStr, _ := res[0]["db_size"].(string) dbSize = dir.FormatFileSize(converter.StringToInt64(dbSizeStr)) } @@ -370,7 +372,7 @@ func (ds *dashboardService) GetDatabaseSize() (dbSize string) { if err != nil { log.Warnf("get db size failed: %s", err) } else { - if res != nil && len(res) > 0 && res[0]["db_size"] != nil { + if len(res) > 0 && res[0]["db_size"] != nil { dbSizeStr, _ := res[0]["db_size"].(int32) dbSize = dir.FormatFileSize(int64(dbSizeStr)) } diff --git a/internal/service/file_record/file_record_service.go b/internal/service/file_record/file_record_service.go index 29097ba8..aa526f01 100644 --- a/internal/service/file_record/file_record_service.go +++ b/internal/service/file_record/file_record_service.go @@ -174,7 +174,6 @@ func (fs *FileRecordService) PurgeDeletedFiles(ctx context.Context) { if err != nil { log.Errorf("create deleted directory error: %v", err) } - return } func (fs *FileRecordService) DeleteAndMoveFileRecord(ctx context.Context, fileRecord *entity.FileRecord) error { diff --git a/internal/service/importer/importer_service.go b/internal/service/importer/importer_service.go index 45aabf39..c7673ffb 100644 --- a/internal/service/importer/importer_service.go +++ b/internal/service/importer/importer_service.go @@ -62,8 +62,7 @@ type ImporterFunc struct { } func (ipfunc *ImporterFunc) AddQuestion(ctx context.Context, questionInfo plugin.QuestionImporterInfo) (err error) { - ipfunc.importerService.ImportQuestion(ctx, questionInfo) - return nil + return ipfunc.importerService.ImportQuestion(ctx, questionInfo) } func (ip *ImporterService) NewImporterFunc() plugin.ImporterFunc { @@ -84,7 +83,7 @@ func (ip *ImporterService) ImportQuestion(ctx context.Context, questionInfo plug return err } if !exist { - return fmt.Errorf("User not found") + return fmt.Errorf("user not found") } // To limit rate, remove the following code from comment: Part 2/2 diff --git a/internal/service/meta/meta_service.go b/internal/service/meta/meta_service.go index 4b310419..c1ca7c61 100644 --- a/internal/service/meta/meta_service.go +++ b/internal/service/meta/meta_service.go @@ -97,7 +97,8 @@ func (ms *MetaService) AddOrUpdateReaction(ctx context.Context, req *schema.Upda return nil, err } var event *schema.EventMsg - if objectType == constant.AnswerObjectType { + switch objectType { + case constant.AnswerObjectType: answerInfo, exist, err := ms.answerRepo.GetAnswer(ctx, req.ObjectID) if err != nil { return nil, err @@ -107,7 +108,7 @@ func (ms *MetaService) AddOrUpdateReaction(ctx context.Context, req *schema.Upda } event = schema.NewEvent(constant.EventAnswerReact, req.UserID).TID(answerInfo.ID). AID(answerInfo.ID, answerInfo.UserID) - } else if objectType == constant.QuestionObjectType { + case constant.QuestionObjectType: questionInfo, exist, err := ms.questionRepo.GetQuestion(ctx, req.ObjectID) if err != nil { return nil, err @@ -117,7 +118,7 @@ func (ms *MetaService) AddOrUpdateReaction(ctx context.Context, req *schema.Upda } event = schema.NewEvent(constant.EventQuestionReact, req.UserID).TID(questionInfo.ID). QID(questionInfo.ID, questionInfo.UserID) - } else { + default: return nil, myErrors.BadRequest(reason.ObjectNotFound) } @@ -159,9 +160,10 @@ func (ms *MetaService) AddOrUpdateReaction(ctx context.Context, req *schema.Upda // updateReaction update reaction func (ms *MetaService) updateReaction(req *schema.UpdateReactionReq, reactions *schema.ReactionsSummaryMeta) { - if req.Reaction == "activate" { + switch req.Reaction { + case "activate": reactions.AddReactionSummary(req.Emoji, req.UserID) - } else if req.Reaction == "deactivate" { + case "deactivate": reactions.RemoveReactionSummary(req.Emoji, req.UserID) } } diff --git a/internal/service/notification/invite_answer_notification.go b/internal/service/notification/invite_answer_notification.go index 4e7c051c..f68feb06 100644 --- a/internal/service/notification/invite_answer_notification.go +++ b/internal/service/notification/invite_answer_notification.go @@ -70,7 +70,7 @@ func (ns *ExternalNotificationService) sendInviteAnswerNotificationEmail(ctx con // If receiver has set language, use it to send email. if len(lang) > 0 { - ctx = context.WithValue(ctx, constant.AcceptLanguageFlag, i18n.Language(lang)) + ctx = context.WithValue(ctx, constant.AcceptLanguageContextKey, i18n.Language(lang)) } title, body, err := ns.emailService.NewInviteAnswerTemplate(ctx, rawData) if err != nil { diff --git a/internal/service/notification/new_answer_notification.go b/internal/service/notification/new_answer_notification.go index 91b7e2ae..c54fd961 100644 --- a/internal/service/notification/new_answer_notification.go +++ b/internal/service/notification/new_answer_notification.go @@ -70,7 +70,7 @@ func (ns *ExternalNotificationService) sendNewAnswerNotificationEmail(ctx contex // If receiver has set language, use it to send email. if len(lang) > 0 { - ctx = context.WithValue(ctx, constant.AcceptLanguageFlag, i18n.Language(lang)) + ctx = context.WithValue(ctx, constant.AcceptLanguageContextKey, i18n.Language(lang)) } title, body, err := ns.emailService.NewAnswerTemplate(ctx, rawData) if err != nil { diff --git a/internal/service/notification/new_comment_notification.go b/internal/service/notification/new_comment_notification.go index 3ec99d13..e622ed4f 100644 --- a/internal/service/notification/new_comment_notification.go +++ b/internal/service/notification/new_comment_notification.go @@ -69,7 +69,7 @@ func (ns *ExternalNotificationService) sendNewCommentNotificationEmail(ctx conte } // If receiver has set language, use it to send email. if len(lang) > 0 { - ctx = context.WithValue(ctx, constant.AcceptLanguageFlag, i18n.Language(lang)) + ctx = context.WithValue(ctx, constant.AcceptLanguageContextKey, i18n.Language(lang)) } title, body, err := ns.emailService.NewCommentTemplate(ctx, rawData) if err != nil { diff --git a/internal/service/notification/new_question_notification.go b/internal/service/notification/new_question_notification.go index 8a12d0b8..debfb8c2 100644 --- a/internal/service/notification/new_question_notification.go +++ b/internal/service/notification/new_question_notification.go @@ -176,7 +176,7 @@ func (ns *ExternalNotificationService) sendNewQuestionNotificationEmail(ctx cont } // If receiver has set language, use it to send email. if len(userInfo.Language) > 0 { - ctx = context.WithValue(ctx, constant.AcceptLanguageFlag, i18n.Language(userInfo.Language)) + ctx = context.WithValue(ctx, constant.AcceptLanguageContextKey, i18n.Language(userInfo.Language)) } title, body, err := ns.emailService.NewQuestionTemplate(ctx, rawData) if err != nil { diff --git a/internal/service/notification/notification_service.go b/internal/service/notification/notification_service.go index 09d87135..0369d455 100644 --- a/internal/service/notification/notification_service.go +++ b/internal/service/notification/notification_service.go @@ -82,8 +82,8 @@ func (ns *NotificationService) GetRedDot(ctx context.Context, req *schema.GetRed achievementKey := fmt.Sprintf(constant.RedDotCacheKey, constant.NotificationTypeAchievement, req.UserID) redBot := &schema.RedDot{} - redBot.Inbox, _, err = ns.data.Cache.GetInt64(ctx, inboxKey) - redBot.Achievement, _, err = ns.data.Cache.GetInt64(ctx, achievementKey) + redBot.Inbox, _, _ = ns.data.Cache.GetInt64(ctx, inboxKey) + redBot.Achievement, _, _ = ns.data.Cache.GetInt64(ctx, achievementKey) // get review amount if req.CanReviewAnswer || req.CanReviewQuestion || req.CanReviewTag { diff --git a/internal/service/notification_common/notification.go b/internal/service/notification_common/notification.go index 2bceb629..55d63842 100644 --- a/internal/service/notification_common/notification.go +++ b/internal/service/notification_common/notification.go @@ -206,6 +206,9 @@ func (ns *NotificationCommon) AddNotification(ctx context.Context, msg *schema.N } if req.ObjectInfo.ObjectType == constant.BadgeAwardObjectType { err = ns.AddBadgeAwardAlertCache(ctx, info.UserID, info.ID, req.ObjectInfo.ObjectMap["badge_id"]) + if err != nil { + log.Error("AddBadgeAwardAlertCache Error", err.Error()) + } } go ns.SendNotificationToAllFollower(ctx, msg, questionID) diff --git a/internal/service/report_handle/report_handle.go b/internal/service/report_handle/report_handle.go index 27cffb11..a0468166 100644 --- a/internal/service/report_handle/report_handle.go +++ b/internal/service/report_handle/report_handle.go @@ -112,6 +112,9 @@ func (rh *ReportHandle) updateReportedAnswerReport(ctx context.Context, report * NoNeedReview: true, }) } + if err != nil { + return err + } return nil } @@ -128,5 +131,8 @@ func (rh *ReportHandle) updateReportedCommentReport(ctx context.Context, report UserID: req.UserID, }) } + if err != nil { + return err + } return nil } diff --git a/internal/service/review/review_service.go b/internal/service/review/review_service.go index 40089fb2..a23b9ee4 100644 --- a/internal/service/review/review_service.go +++ b/internal/service/review/review_service.go @@ -469,7 +469,6 @@ func (cs *ReviewService) notificationCommentOnTheQuestion(ctx context.Context, c cs.notificationAnswerComment(ctx, objInfo.QuestionID, objInfo.Title, objInfo.AnswerID, objInfo.ObjectCreatorUserID, comment.ID, comment.UserID, htmltext.FetchExcerpt(comment.ParsedText, "...", 240)) } - return } func (cs *ReviewService) notificationCommentReply(ctx context.Context, replyUserID, commentID, commentUserID, diff --git a/internal/service/siteinfo/siteinfo_service.go b/internal/service/siteinfo/siteinfo_service.go index cf43d68d..f355d09f 100644 --- a/internal/service/siteinfo/siteinfo_service.go +++ b/internal/service/siteinfo/siteinfo_service.go @@ -345,7 +345,7 @@ func (s *SiteInfoService) GetPrivilegesConfig(ctx context.Context) (resp *schema return nil, err } privilegeOptions := schema.DefaultPrivilegeOptions - if privilege.CustomPrivileges != nil && len(privilege.CustomPrivileges) > 0 { + if len(privilege.CustomPrivileges) > 0 { privilegeOptions = append(privilegeOptions, &schema.PrivilegeOption{ Level: schema.PrivilegeLevelCustom, LevelDesc: reason.PrivilegeLevelCustomDesc, @@ -358,7 +358,7 @@ func (s *SiteInfoService) GetPrivilegesConfig(ctx context.Context) (resp *schema Options: s.translatePrivilegeOptions(ctx, privilegeOptions), SelectedLevel: schema.PrivilegeLevel3, } - if privilege != nil && privilege.Level > 0 { + if privilege.Level > 0 { resp.SelectedLevel = privilege.Level } return resp, nil diff --git a/internal/service/uploader/upload.go b/internal/service/uploader/upload.go index 2ae5369d..30029193 100644 --- a/internal/service/uploader/upload.go +++ b/internal/service/uploader/upload.go @@ -119,7 +119,9 @@ func (us *uploaderService) UploadAvatarFile(ctx *gin.Context, userID string) (ur if err != nil { return "", errors.BadRequest(reason.RequestFormatError).WithError(err) } - file.Close() + defer func() { + _ = file.Close() + }() fileExt := strings.ToLower(path.Ext(fileHeader.Filename)) if _, ok := plugin.DefaultFileTypeCheckMapping[plugin.UserAvatar][fileExt]; !ok { return "", errors.BadRequest(reason.RequestFormatError).WithError(err) @@ -148,12 +150,12 @@ func (us *uploaderService) AvatarThumbFile(ctx *gin.Context, fileName string, si thumbFileName := fmt.Sprintf("%d_%d@%s", size, size, fileName) thumbFilePath := fmt.Sprintf("%s/%s/%s", us.serviceConfig.UploadPath, constant.AvatarThumbSubPath, thumbFileName) - avatarFile, err := os.ReadFile(thumbFilePath) + _, err = os.ReadFile(thumbFilePath) if err == nil { return thumbFilePath, nil } filePath := fmt.Sprintf("%s/%s/%s", us.serviceConfig.UploadPath, constant.AvatarSubPath, fileName) - avatarFile, err = os.ReadFile(filePath) + avatarFile, err := os.ReadFile(filePath) if err != nil { return "", errors.NotFound(reason.UnknownError).WithError(err) } @@ -179,7 +181,9 @@ func (us *uploaderService) AvatarThumbFile(ctx *gin.Context, fileName string, si if err != nil { return "", errors.InternalServer(reason.UnknownError).WithError(err).WithStack() } - defer out.Close() + defer func() { + _ = out.Close() + }() thumbReader := bytes.NewReader(buf.Bytes()) if _, err = io.Copy(out, thumbReader); err != nil { @@ -208,7 +212,9 @@ func (us *uploaderService) UploadPostFile(ctx *gin.Context, userID string) ( if err != nil { return "", errors.BadRequest(reason.RequestFormatError).WithError(err) } - defer file.Close() + defer func() { + _ = file.Close() + }() if checker.IsUnAuthorizedExtension(fileHeader.Filename, siteWrite.AuthorizedImageExtensions) { return "", errors.BadRequest(reason.RequestFormatError).WithError(err) } @@ -244,7 +250,9 @@ func (us *uploaderService) UploadPostAttachment(ctx *gin.Context, userID string) if err != nil { return "", errors.BadRequest(reason.RequestFormatError).WithError(err) } - defer file.Close() + defer func() { + _ = file.Close() + }() if checker.IsUnAuthorizedExtension(fileHeader.Filename, resp.AuthorizedAttachmentExtensions) { return "", errors.BadRequest(reason.RequestFormatError).WithError(err) } @@ -280,7 +288,9 @@ func (us *uploaderService) UploadBrandingFile(ctx *gin.Context, userID string) ( if err != nil { return "", errors.BadRequest(reason.RequestFormatError).WithError(err) } - file.Close() + defer func() { + _ = file.Close() + }() fileExt := strings.ToLower(path.Ext(fileHeader.Filename)) if _, ok := plugin.DefaultFileTypeCheckMapping[plugin.AdminBranding][fileExt]; !ok { return "", errors.BadRequest(reason.RequestFormatError).WithError(err) @@ -316,7 +326,9 @@ func (us *uploaderService) uploadImageFile(ctx *gin.Context, file *multipart.Fil if err != nil { return "", errors.InternalServer(reason.UnknownError).WithError(err).WithStack() } - defer src.Close() + defer func() { + _ = src.Close() + }() if !checker.DecodeAndCheckImageFile(filePath, siteWrite.GetMaxImageMegapixel()) { return "", errors.BadRequest(reason.UploadFileUnsupportedFileFormat) diff --git a/internal/service/user_admin/user_backyard.go b/internal/service/user_admin/user_backyard.go index 0f6ec81e..6fce161c 100644 --- a/internal/service/user_admin/user_backyard.go +++ b/internal/service/user_admin/user_backyard.go @@ -400,7 +400,7 @@ func (us *UserAdminService) EditUserProfile(ctx context.Context, req *schema.Edi if req.UserID == req.LoginUserID { return nil, errors.BadRequest(reason.AdminCannotEditTheirProfile) } - userInfo, exist, err := us.userRepo.GetUserInfo(ctx, req.UserID) + _, exist, err := us.userRepo.GetUserInfo(ctx, req.UserID) if err != nil { return nil, err } @@ -415,7 +415,7 @@ func (us *UserAdminService) EditUserProfile(ctx context.Context, req *schema.Edi }), errors.BadRequest(reason.UsernameInvalid) } - userInfo, exist, err = us.userCommonService.GetByUsername(ctx, req.Username) + userInfo, exist, err := us.userCommonService.GetByUsername(ctx, req.Username) if err != nil { return nil, err } @@ -620,11 +620,12 @@ func (us *UserAdminService) SendUserActivation(ctx context.Context, req *schema. } func (us *UserAdminService) DeletePermanently(ctx context.Context, req *schema.DeletePermanentlyReq) (err error) { - if req.Type == constant.DeletePermanentlyUsers { + switch req.Type { + case constant.DeletePermanentlyUsers: return us.userRepo.DeletePermanentlyUsers(ctx) - } else if req.Type == constant.DeletePermanentlyQuestions { + case constant.DeletePermanentlyQuestions: return us.questionCommonRepo.DeletePermanentlyQuestions(ctx) - } else if req.Type == constant.DeletePermanentlyAnswers { + case constant.DeletePermanentlyAnswers: return us.answerCommonRepo.DeletePermanentlyAnswers(ctx) } diff --git a/internal/service/user_notification_config/user_notification_config_service.go b/internal/service/user_notification_config/user_notification_config_service.go index 01da3ee2..c40df55c 100644 --- a/internal/service/user_notification_config/user_notification_config_service.go +++ b/internal/service/user_notification_config/user_notification_config_service.go @@ -68,21 +68,21 @@ func (us *UserNotificationConfigService) GetUserNotificationConfig(ctx context.C func (us *UserNotificationConfigService) UpdateUserNotificationConfig( ctx context.Context, req *schema.UpdateUserNotificationConfigReq) (err error) { - req.NotificationConfig.Format() + req.Format() err = us.userNotificationConfigRepo.Save(ctx, - us.convertToEntity(ctx, req.UserID, constant.InboxSource, req.NotificationConfig.Inbox)) + us.convertToEntity(ctx, req.UserID, constant.InboxSource, req.Inbox)) if err != nil { return err } err = us.userNotificationConfigRepo.Save(ctx, - us.convertToEntity(ctx, req.UserID, constant.AllNewQuestionSource, req.NotificationConfig.AllNewQuestion)) + us.convertToEntity(ctx, req.UserID, constant.AllNewQuestionSource, req.AllNewQuestion)) if err != nil { return err } err = us.userNotificationConfigRepo.Save(ctx, us.convertToEntity(ctx, req.UserID, constant.AllNewQuestionForFollowingTagsSource, - req.NotificationConfig.AllNewQuestionForFollowingTags)) + req.AllNewQuestionForFollowingTags)) if err != nil { return err } diff --git a/pkg/checker/file_type.go b/pkg/checker/file_type.go index 51f687d6..ac1fbcaf 100644 --- a/pkg/checker/file_type.go +++ b/pkg/checker/file_type.go @@ -75,7 +75,9 @@ func decodeAndCheckImageFile(localFilePath string, maxImageMegapixel int, checke log.Errorf("open file error: %v", err) return false } - defer file.Close() + defer func() { + _ = file.Close() + }() if err = checker(file, maxImageMegapixel); err != nil { log.Errorf("check image format error: %v", err) diff --git a/pkg/checker/password.go b/pkg/checker/password.go index ac274f35..ac99fd43 100644 --- a/pkg/checker/password.go +++ b/pkg/checker/password.go @@ -20,6 +20,7 @@ package checker import ( + "errors" "fmt" "regexp" "strings" @@ -40,7 +41,7 @@ const ( // CheckPassword checks the password strength func CheckPassword(password string) error { if strings.Contains(password, " ") { - return fmt.Errorf(PasswordCannotContainSpaces) + return errors.New(PasswordCannotContainSpaces) } // TODO Currently there is no requirement for password strength diff --git a/pkg/converter/markdown.go b/pkg/converter/markdown.go index 1789a32c..d16915a8 100644 --- a/pkg/converter/markdown.go +++ b/pkg/converter/markdown.go @@ -32,7 +32,6 @@ import ( "github.com/yuin/goldmark/extension" "github.com/yuin/goldmark/parser" "github.com/yuin/goldmark/renderer" - "github.com/yuin/goldmark/renderer/html" goldmarkHTML "github.com/yuin/goldmark/renderer/html" "github.com/yuin/goldmark/util" ) @@ -141,7 +140,7 @@ func (r *DangerousHTMLRenderer) renderLink(w util.BufWriter, source []byte, node if entering && r.renderLinkIsUrl(string(n.Destination)) { _, _ = w.WriteString("<a href=\"") // _, _ = w.WriteString("<a test=\"1\" rel=\"nofollow\" href=\"") - if r.Unsafe || !html.IsDangerousURL(n.Destination) { + if r.Unsafe || !goldmarkHTML.IsDangerousURL(n.Destination) { _, _ = w.Write(util.EscapeHTML(util.URLEscape(n.Destination, true))) } _ = w.WriteByte('"') @@ -151,7 +150,7 @@ func (r *DangerousHTMLRenderer) renderLink(w util.BufWriter, source []byte, node _ = w.WriteByte('"') } if n.Attributes() != nil { - html.RenderAttributes(w, n, html.LinkAttributeFilter) + goldmarkHTML.RenderAttributes(w, n, goldmarkHTML.LinkAttributeFilter) } _ = w.WriteByte('>') } else { @@ -175,7 +174,7 @@ func (r *DangerousHTMLRenderer) renderAutoLink(w util.BufWriter, source []byte, _, _ = w.Write(util.EscapeHTML(util.URLEscape(url, false))) if n.Attributes() != nil { _ = w.WriteByte('"') - html.RenderAttributes(w, n, html.LinkAttributeFilter) + goldmarkHTML.RenderAttributes(w, n, goldmarkHTML.LinkAttributeFilter) _ = w.WriteByte('>') } else { _, _ = w.WriteString(`">`) diff --git a/pkg/htmltext/htmltext.go b/pkg/htmltext/htmltext.go index 707c20a8..56db4d2b 100644 --- a/pkg/htmltext/htmltext.go +++ b/pkg/htmltext/htmltext.go @@ -194,7 +194,9 @@ func GetPicByUrl(Url string) string { if err != nil { return "" } - defer res.Body.Close() + defer func() { + _ = res.Body.Close() + }() pix, err := io.ReadAll(res.Body) if err != nil { return "" diff --git a/plugin/kv_storage.go b/plugin/kv_storage.go index d1ed3eaa..204e5ee6 100644 --- a/plugin/kv_storage.go +++ b/plugin/kv_storage.go @@ -88,7 +88,7 @@ func (kv *KVOperator) getSession(ctx context.Context) (*xorm.Session, func()) { session = kv.data.DB.NewSession().Context(ctx) cleanup = func() { if session != nil { - session.Close() + _ = session.Close() } } } @@ -281,7 +281,7 @@ func (kv *KVOperator) Tx(ctx context.Context, fn func(ctx context.Context, kv *K if kv.session == nil { session := kv.data.DB.NewSession().Context(ctx) if err := session.Begin(); err != nil { - session.Close() + _ = session.Close() return fmt.Errorf("%w: begin transaction failed: %v", ErrKVTransactionFailed, err) } @@ -291,7 +291,7 @@ func (kv *KVOperator) Tx(ctx context.Context, fn func(ctx context.Context, kv *K log.Errorf("rollback failed: %v", rollbackErr) } } - session.Close() + _ = session.Close() }() txKv = &KVOperator{ diff --git a/plugin/plugin_test/plugin_main_test.go b/plugin/plugin_test/plugin_main_test.go index add11460..fd9015c8 100644 --- a/plugin/plugin_test/plugin_main_test.go +++ b/plugin/plugin_test/plugin_main_test.go @@ -78,7 +78,7 @@ func TestMain(t *testing.M) { dbSetting = dbSettingMapping[string(schemas.SQLITE)] } if dbSetting.Driver == string(schemas.SQLITE) { - os.RemoveAll(dbSetting.Connection) + _ = os.RemoveAll(dbSetting.Connection) } defer func() { diff --git a/ui/static.go b/ui/static.go index dc79a178..65caae46 100644 --- a/ui/static.go +++ b/ui/static.go @@ -21,7 +21,6 @@ package ui import ( "embed" - _ "embed" ) //go:embed build
