From 7331353b5131012efb6e36ba291f3f5804ba8dbe Mon Sep 17 00:00:00 2001 From: LinkinStar Date: Fri, 16 Dec 2022 14:31:38 +0800 Subject: [PATCH 1/6] style(io): replace deprecated io function --- internal/base/middleware/avatar.go | 4 ++-- internal/service/dashboard/dashboard_service.go | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/internal/base/middleware/avatar.go b/internal/base/middleware/avatar.go index 3a6ce2da..b7cd4eef 100644 --- a/internal/base/middleware/avatar.go +++ b/internal/base/middleware/avatar.go @@ -2,8 +2,8 @@ package middleware import ( "fmt" - "io/ioutil" "net/url" + "os" "path/filepath" "strings" @@ -44,7 +44,7 @@ func (am *AvatarMiddleware) AvatarThumb() gin.HandlerFunc { filePath := fmt.Sprintf("%s/avatar/%s", uploadPath, urlfileName) var avatarfile []byte if size == 0 { - avatarfile, err = ioutil.ReadFile(filePath) + avatarfile, err = os.ReadFile(filePath) } else { avatarfile, err = am.uploaderService.AvatarThumbFile(ctx, uploadPath, urlfileName, size) } diff --git a/internal/service/dashboard/dashboard_service.go b/internal/service/dashboard/dashboard_service.go index 8495ab0a..11868acd 100644 --- a/internal/service/dashboard/dashboard_service.go +++ b/internal/service/dashboard/dashboard_service.go @@ -4,7 +4,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "net/url" "time" @@ -208,7 +208,7 @@ func (ds *DashboardService) RemoteVersion(ctx context.Context) string { } defer resp.Body.Close() - respByte, err := ioutil.ReadAll(resp.Body) + respByte, err := io.ReadAll(resp.Body) if err != nil { log.Error("http.Client error", err) return "" From 6a43e561757abcad4235f9e40c8f3dd75285c24a Mon Sep 17 00:00:00 2001 From: LinkinStar Date: Fri, 16 Dec 2022 14:33:36 +0800 Subject: [PATCH 2/6] style(tag): Incorrect error handling --- internal/service/search_parser/search_parser.go | 2 +- internal/service/siteinfo_common/siteinfo_service_test.go | 3 ++- internal/service/tag_common/tag_common.go | 3 +++ 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/internal/service/search_parser/search_parser.go b/internal/service/search_parser/search_parser.go index 3fbbba56..bd8db3f9 100644 --- a/internal/service/search_parser/search_parser.go +++ b/internal/service/search_parser/search_parser.go @@ -191,7 +191,7 @@ func (sp *SearchParser) parseUserID(query *string, currentUserID string) (userID res := re.FindStringSubmatch(q) if len(res) == 2 { name := res[1] - user, has, err := sp.userCommon.GetUserBasicInfoByUserName(nil, name) + user, has, err := sp.userCommon.GetUserBasicInfoByUserName(context.TODO(), name) if err == nil && has { userID = user.ID q = re.ReplaceAllString(q, "") diff --git a/internal/service/siteinfo_common/siteinfo_service_test.go b/internal/service/siteinfo_common/siteinfo_service_test.go index b3e15a22..4d80c67a 100644 --- a/internal/service/siteinfo_common/siteinfo_service_test.go +++ b/internal/service/siteinfo_common/siteinfo_service_test.go @@ -1,6 +1,7 @@ package siteinfo_common import ( + "context" "testing" "github.com/answerdev/answer/internal/base/constant" @@ -25,7 +26,7 @@ func TestSiteInfoCommonService_GetSiteGeneral(t *testing.T) { defer ctl.Finish() mockInit(ctl) siteInfoCommonService := NewSiteInfoCommonService(mockSiteInfoRepo) - resp, err := siteInfoCommonService.GetSiteGeneral(nil) + resp, err := siteInfoCommonService.GetSiteGeneral(context.TODO()) assert.NoError(t, err) assert.Equal(t, resp.Name, "name") } diff --git a/internal/service/tag_common/tag_common.go b/internal/service/tag_common/tag_common.go index dfdb832a..4f167bd9 100644 --- a/internal/service/tag_common/tag_common.go +++ b/internal/service/tag_common/tag_common.go @@ -212,6 +212,9 @@ func (ts *TagCommonService) ExistRecommend(ctx context.Context, tags []*schema.T // GetObjectTag get object tag func (ts *TagCommonService) GetObjectTag(ctx context.Context, objectId string) (objTags []*schema.TagResp, err error) { tagsInfoList, err := ts.GetObjectEntityTag(ctx, objectId) + if err != nil { + return nil, err + } return ts.TagFormat(ctx, tagsInfoList) } From fb4d0cc3cd713451b8fce04815d0d37de559534f Mon Sep 17 00:00:00 2001 From: LinkinStar Date: Fri, 16 Dec 2022 14:35:01 +0800 Subject: [PATCH 3/6] style(object): Remove unneeded initialization --- internal/service/object_info/object_info.go | 2 -- 1 file changed, 2 deletions(-) diff --git a/internal/service/object_info/object_info.go b/internal/service/object_info/object_info.go index 9ab18e70..fcf782fb 100644 --- a/internal/service/object_info/object_info.go +++ b/internal/service/object_info/object_info.go @@ -40,8 +40,6 @@ func NewObjService( } } func (os *ObjService) GetUnreviewedRevisionInfo(ctx context.Context, objectID string) (objInfo *schema.UnreviewedRevisionInfoInfo, err error) { - objInfo = &schema.UnreviewedRevisionInfoInfo{} - objectType, err := obj.GetObjectTypeStrByObjectID(objectID) if err != nil { return nil, err From a4f5f8ecc30a4d548e1b385ebfe971bb3976a552 Mon Sep 17 00:00:00 2001 From: LinkinStar Date: Fri, 16 Dec 2022 14:41:20 +0800 Subject: [PATCH 4/6] style(simple): Simplify code --- internal/base/constant/constant.go | 5 +---- internal/controller/template_controller.go | 2 +- internal/controller/template_render/controller.go | 6 +++--- internal/install/install_controller.go | 1 - internal/migrations/init.go | 3 +++ internal/service/export/email_service.go | 3 +++ internal/service/question_service.go | 3 --- internal/service/report_backyard/report_backyard.go | 7 +++++++ internal/service/revision_service.go | 2 +- internal/service/role/role_service.go | 1 - internal/service/search_parser/search_parser.go | 12 ++++++------ internal/service/tag_common/tag_common.go | 5 ++++- 12 files changed, 29 insertions(+), 21 deletions(-) diff --git a/internal/base/constant/constant.go b/internal/base/constant/constant.go index a1d09667..40990b93 100644 --- a/internal/base/constant/constant.go +++ b/internal/base/constant/constant.go @@ -69,8 +69,5 @@ const ( func ExistInPathIgnore(name string) bool { _, ok := PathIgnoreMap[name] - if ok { - return true - } - return false + return ok } diff --git a/internal/controller/template_controller.go b/internal/controller/template_controller.go index bfc2299f..2c7eaec7 100644 --- a/internal/controller/template_controller.go +++ b/internal/controller/template_controller.go @@ -104,7 +104,7 @@ func (tc *TemplateController) Index(ctx *gin.Context) { } siteInfo := tc.SiteInfo(ctx) - siteInfo.Canonical = fmt.Sprintf("%s", siteInfo.General.SiteUrl) + siteInfo.Canonical = siteInfo.General.SiteUrl UrlUseTitle := false if siteInfo.SiteSeo.PermaLink == schema.PermaLinkQuestionIDAndTitle { diff --git a/internal/controller/template_render/controller.go b/internal/controller/template_render/controller.go index bf5d5f8d..f44c1ea6 100644 --- a/internal/controller/template_render/controller.go +++ b/internal/controller/template_render/controller.go @@ -76,21 +76,21 @@ func Paginator(page, pageSize int, nums int64) *schema.Paginator { prevpage = page - 1 nextpage = int(math.Min(float64(totalpages), float64(page+1))) pages = make([]int, 5) - for i, _ := range pages { + for i := range pages { pages[i] = start + i } case page >= 3 && totalpages > 5: start := page - 3 + 1 pages = make([]int, 5) prevpage = page - 3 - for i, _ := range pages { + for i := range pages { pages[i] = start + i } prevpage = page - 1 nextpage = page + 1 default: pages = make([]int, int(math.Min(5, float64(totalpages)))) - for i, _ := range pages { + for i := range pages { pages[i] = i + 1 } prevpage = int(math.Max(float64(1), float64(page-1))) diff --git a/internal/install/install_controller.go b/internal/install/install_controller.go index 62cbdf87..561c6dc4 100644 --- a/internal/install/install_controller.go +++ b/internal/install/install_controller.go @@ -187,5 +187,4 @@ func InitBaseInfo(ctx *gin.Context) { time.Sleep(1 * time.Second) os.Exit(0) }() - return } diff --git a/internal/migrations/init.go b/internal/migrations/init.go index 86f7e60c..5bbc4631 100644 --- a/internal/migrations/init.go +++ b/internal/migrations/init.go @@ -116,6 +116,9 @@ func initSiteInfo(engine *xorm.Engine, language, siteName, siteURL, contactEmail Content: string(generalDataBytes), Status: 1, }) + if err != nil { + return err + } loginConfig := map[string]bool{ "allow_new_registrations": true, diff --git a/internal/service/export/email_service.go b/internal/service/export/email_service.go index e89dfb19..9f078224 100644 --- a/internal/service/export/email_service.go +++ b/internal/service/export/email_service.go @@ -277,6 +277,9 @@ func (es *EmailService) TestTemplate(ctx context.Context) (title, body string, e return "", "", fmt.Errorf("email test body template parse error: %s", err) } tmpl, err = template.New("test_body").Parse(ec.TestBody) + if err != nil { + return "", "", fmt.Errorf("test_body template parse error: %s", err) + } err = tmpl.Execute(bodyBuf, templateData) if err != nil { return "", "", err diff --git a/internal/service/question_service.go b/internal/service/question_service.go index 4d8c1b98..7a4635a0 100644 --- a/internal/service/question_service.go +++ b/internal/service/question_service.go @@ -1044,9 +1044,6 @@ func (qs *QuestionService) SitemapCron(ctx context.Context) { if setCacheErr := qs.SetCache(ctx, schema.SitemapCachekey, data); setCacheErr != nil { log.Errorf("set sitemap cron SetCache failed: %s", setCacheErr) } - - return - } func (qs *QuestionService) SetCache(ctx context.Context, cachekey string, info interface{}) error { diff --git a/internal/service/report_backyard/report_backyard.go b/internal/service/report_backyard/report_backyard.go index 69b87c85..2ab1a595 100644 --- a/internal/service/report_backyard/report_backyard.go +++ b/internal/service/report_backyard/report_backyard.go @@ -2,6 +2,7 @@ package report_backyard import ( "context" + "github.com/answerdev/answer/internal/service/config" "github.com/answerdev/answer/pkg/htmltext" @@ -84,9 +85,15 @@ func (rs *ReportBackyardService) ListReportPage(ctx context.Context, dto schema. // flagged users flaggedUsers, err = rs.commonUser.BatchUserBasicInfoByID(ctx, flaggedUserIds) + if err != nil { + return nil, err + } // flag users users, err = rs.commonUser.BatchUserBasicInfoByID(ctx, userIds) + if err != nil { + return nil, err + } for _, r := range resp { r.ReportedUser = flaggedUsers[r.ReportedUserID] r.ReportUser = users[r.UserID] diff --git a/internal/service/revision_service.go b/internal/service/revision_service.go index 84624cea..bb65db32 100644 --- a/internal/service/revision_service.go +++ b/internal/service/revision_service.go @@ -305,7 +305,7 @@ func (rs *RevisionService) GetUnreviewedRevisionPage(ctx context.Context, req *s } if exists { var uinfo schema.UserBasicInfo - err = copier.Copy(&uinfo, userInfo) + _ = copier.Copy(&uinfo, userInfo) item.UnreviewedInfo.UserInfo = uinfo } revisionResp = append(revisionResp, item) diff --git a/internal/service/role/role_service.go b/internal/service/role/role_service.go index bebad7c8..ae18f762 100644 --- a/internal/service/role/role_service.go +++ b/internal/service/role/role_service.go @@ -81,5 +81,4 @@ func (rs *RoleService) translateRole(ctx context.Context, role *entity.Role) { role.Name = translator.GlobalTrans.Tr(handler.GetLangByCtx(ctx), trRoleNameModerator) role.Description = translator.GlobalTrans.Tr(handler.GetLangByCtx(ctx), trRoleDescriptionModerator) } - return } diff --git a/internal/service/search_parser/search_parser.go b/internal/service/search_parser/search_parser.go index bd8db3f9..781247f7 100644 --- a/internal/service/search_parser/search_parser.go +++ b/internal/service/search_parser/search_parser.go @@ -49,7 +49,7 @@ func (sp *SearchParser) ParseStructure(dto *schema.SearchDTO) ( all = 0 q = 0 a = 0 - withWords = []string{} + withWords []string limitWords = 5 ) @@ -196,7 +196,7 @@ func (sp *SearchParser) parseUserID(query *string, currentUserID string) (userID userID = user.ID q = re.ReplaceAllString(q, "") } - } else if strings.Index(q, exprMe) != -1 { + } else if strings.Contains(q, exprMe) { userID = currentUserID q = strings.ReplaceAll(q, exprMe, "") } @@ -247,7 +247,7 @@ func (sp *SearchParser) parseNotAccepted(query *string) (notAccepted bool) { expr = `hasaccepted:no` ) - if strings.Index(q, expr) != -1 { + if strings.Contains(q, expr) { q = strings.ReplaceAll(q, expr, "") notAccepted = true } @@ -263,7 +263,7 @@ func (sp *SearchParser) parseIsQuestion(query *string) (isQuestion bool) { expr = `is:question` ) - if strings.Index(q, expr) == 0 { + if strings.Contains(q, expr) { q = strings.ReplaceAll(q, expr, "") isQuestion = true } @@ -316,7 +316,7 @@ func (sp *SearchParser) parseAccepted(query *string) (accepted bool) { expr = `isaccepted:yes` ) - if strings.Index(q, expr) != -1 { + if strings.Contains(q, expr) { accepted = true strings.ReplaceAll(q, expr, "") } @@ -350,7 +350,7 @@ func (sp *SearchParser) parseIsAnswer(query *string) (isAnswer bool) { expr = `is:answer` ) - if strings.Index(q, expr) != -1 { + if strings.Contains(q, expr) { isAnswer = true q = strings.ReplaceAll(q, expr, "") } diff --git a/internal/service/tag_common/tag_common.go b/internal/service/tag_common/tag_common.go index 4f167bd9..6af946bb 100644 --- a/internal/service/tag_common/tag_common.go +++ b/internal/service/tag_common/tag_common.go @@ -162,6 +162,9 @@ func (ts *TagCommonService) SetTagsAttribute(ctx context.Context, tags []string, default: return } + if err != nil { + return err + } err = ts.tagCommonRepo.UpdateTagsAttribute(ctx, tagslist, attribute, false) if err != nil { return err @@ -439,7 +442,7 @@ func (ts *TagCommonService) CheckTagsIsChange(ctx context.Context, tagNameList, check[item] = true } for _, value := range check { - if value == false { + if !value { return true } } From 6e1f4841f17b96254f374249abbc18911b75e394 Mon Sep 17 00:00:00 2001 From: LinkinStar Date: Fri, 16 Dec 2022 16:35:55 +0800 Subject: [PATCH 5/6] style(simple): Properly handle unhandled errors --- internal/base/cron/cron.go | 6 +++- internal/base/middleware/avatar.go | 6 +++- internal/controller/question_controller.go | 8 ++--- internal/controller/template_render/tags.go | 3 ++ internal/controller/user_controller.go | 9 +++-- internal/repo/activity/answer_repo.go | 9 ++--- internal/repo/auth/auth.go | 1 - internal/repo/captcha/captcha.go | 3 +- internal/repo/repo_test/comment_repo_test.go | 3 -- internal/repo/repo_test/revision_repo_test.go | 4 ++- internal/repo/repo_test/tag_repo_test.go | 2 +- .../repo/repo_test/user_backyard_repo_test.go | 2 +- internal/repo/report/report_repo.go | 29 ++++++++------- internal/router/ui_test.go | 36 ------------------- internal/service/object_info/object_info.go | 3 ++ .../report_backyard/report_backyard.go | 23 +++++++++--- .../service/report_common/report_common.go | 2 +- .../report_handle_backyard/report_handle.go | 2 +- .../service/search_parser/search_parser.go | 2 +- internal/service/uploader/upload.go | 6 ++-- internal/service/vote_service.go | 1 + 21 files changed, 75 insertions(+), 85 deletions(-) delete mode 100644 internal/router/ui_test.go diff --git a/internal/base/cron/cron.go b/internal/base/cron/cron.go index 2bdd7373..79c34597 100644 --- a/internal/base/cron/cron.go +++ b/internal/base/cron/cron.go @@ -7,6 +7,7 @@ import ( "github.com/answerdev/answer/internal/service" "github.com/answerdev/answer/internal/service/siteinfo_common" "github.com/robfig/cron/v3" + "github.com/segmentfault/pacman/log" ) // ScheduledTaskManager scheduled task manager @@ -31,10 +32,13 @@ func (s *ScheduledTaskManager) Run() { fmt.Println("start cron") s.questionService.SitemapCron(context.Background()) c := cron.New() - c.AddFunc("0 */1 * * *", func() { + _, err := c.AddFunc("0 */1 * * *", func() { ctx := context.Background() fmt.Println("sitemap cron execution") s.questionService.SitemapCron(ctx) }) + if err != nil { + log.Error(err) + } c.Start() } diff --git a/internal/base/middleware/avatar.go b/internal/base/middleware/avatar.go index b7cd4eef..66a72f68 100644 --- a/internal/base/middleware/avatar.go +++ b/internal/base/middleware/avatar.go @@ -11,6 +11,7 @@ import ( "github.com/answerdev/answer/internal/service/uploader" "github.com/answerdev/answer/pkg/converter" "github.com/gin-gonic/gin" + "github.com/segmentfault/pacman/log" ) type AvatarMiddleware struct { @@ -52,7 +53,10 @@ func (am *AvatarMiddleware) AvatarThumb() gin.HandlerFunc { ctx.Next() return } - ctx.Writer.WriteString(string(avatarfile)) + _, err = ctx.Writer.WriteString(string(avatarfile)) + if err != nil { + log.Error(err) + } ctx.Abort() return diff --git a/internal/controller/question_controller.go b/internal/controller/question_controller.go index a49ee277..7a9199b3 100644 --- a/internal/controller/question_controller.go +++ b/internal/controller/question_controller.go @@ -281,9 +281,7 @@ func (qc *QuestionController) AddQuestion(ctx *gin.Context) { if err != nil { errlist, ok := resp.([]*validator.FormErrorField) if ok { - for _, item := range errlist { - errFields = append(errFields, item) - } + errFields = append(errFields, errlist...) } } if len(errFields) > 0 { @@ -335,9 +333,7 @@ func (qc *QuestionController) UpdateQuestion(ctx *gin.Context) { errlist, err := qc.questionService.UpdateQuestionCheckTags(ctx, req) if err != nil { - for _, item := range errlist { - errFields = append(errFields, item) - } + errFields = append(errFields, errlist...) } if len(errFields) > 0 { diff --git a/internal/controller/template_render/tags.go b/internal/controller/template_render/tags.go index 1ef990cd..d8a36b64 100644 --- a/internal/controller/template_render/tags.go +++ b/internal/controller/template_render/tags.go @@ -19,6 +19,9 @@ func (q *TemplateRenderController) TagInfo(ctx context.Context, req *schema.GetT dto := &schema.GetTagInfoReq{} _ = copier.Copy(dto, req) resp, err = q.tagService.GetTagInfo(ctx, dto) + if err != nil { + return + } searchQuestion := &schema.QuestionSearch{} searchQuestion.Page = req.Page searchQuestion.PageSize = req.PageSize diff --git a/internal/controller/user_controller.go b/internal/controller/user_controller.go index 5ab30a52..3be345d2 100644 --- a/internal/controller/user_controller.go +++ b/internal/controller/user_controller.go @@ -15,6 +15,7 @@ import ( "github.com/answerdev/answer/internal/service/uploader" "github.com/gin-gonic/gin" "github.com/segmentfault/pacman/errors" + "github.com/segmentfault/pacman/log" ) // UserController user controller @@ -294,11 +295,13 @@ func (uc *UserController) UserVerifyEmailSend(ctx *gin.Context) { ErrorMsg: translator.GlobalTrans.Tr(handler.GetLang(ctx), reason.CaptchaVerificationFailed), }) handler.HandleResponse(ctx, errors.BadRequest(reason.CaptchaVerificationFailed), errFields) - return } - uc.actionService.ActionRecordAdd(ctx, schema.ActionRecordTypeEmail, ctx.ClientIP()) - err := uc.userService.UserVerifyEmailSend(ctx, userInfo.UserID) + _, err := uc.actionService.ActionRecordAdd(ctx, schema.ActionRecordTypeEmail, ctx.ClientIP()) + if err != nil { + log.Error(err) + } + err = uc.userService.UserVerifyEmailSend(ctx, userInfo.UserID) handler.HandleResponse(ctx, err, nil) } diff --git a/internal/repo/activity/answer_repo.go b/internal/repo/activity/answer_repo.go index 74d9136d..a6eb47cc 100644 --- a/internal/repo/activity/answer_repo.go +++ b/internal/repo/activity/answer_repo.go @@ -27,15 +27,12 @@ type AnswerActivityRepo struct { } const ( - acceptAction = "accept" - acceptedAction = "accepted" - acceptCancelAction = "accept_cancel" - acceptedCancelAction = "accepted_cancel" + acceptAction = "accept" + acceptedAction = "accepted" ) var ( - acceptActionList = []string{acceptAction, acceptedAction} - acceptCancelActionList = []string{acceptCancelAction, acceptedCancelAction} + acceptActionList = []string{acceptAction, acceptedAction} ) // NewAnswerActivityRepo new repository diff --git a/internal/repo/auth/auth.go b/internal/repo/auth/auth.go index 6a5dc61e..b4bd1f19 100644 --- a/internal/repo/auth/auth.go +++ b/internal/repo/auth/auth.go @@ -170,7 +170,6 @@ func (ar *authRepo) RemoveAllUserTokens(ctx context.Context, userID string) { if err := ar.data.Cache.Del(ctx, key); err != nil { log.Error(err) } - return } // NewAuthRepo new repository diff --git a/internal/repo/captcha/captcha.go b/internal/repo/captcha/captcha.go index 73ca1450..13f6d476 100644 --- a/internal/repo/captcha/captcha.go +++ b/internal/repo/captcha/captcha.go @@ -9,6 +9,7 @@ import ( "github.com/answerdev/answer/internal/base/reason" "github.com/answerdev/answer/internal/service/action" "github.com/segmentfault/pacman/errors" + "github.com/segmentfault/pacman/log" ) // captchaRepo captcha repository @@ -65,7 +66,7 @@ func (cr *captchaRepo) SetCaptcha(ctx context.Context, key, captcha string) (err func (cr *captchaRepo) GetCaptcha(ctx context.Context, key string) (captcha string, err error) { captcha, err = cr.data.Cache.GetString(ctx, key) if err != nil { - err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() + log.Debug(err) } // TODO: cache reflect should return empty when key not found return captcha, nil diff --git a/internal/repo/repo_test/comment_repo_test.go b/internal/repo/repo_test/comment_repo_test.go index c7ad1d41..b482cbf1 100644 --- a/internal/repo/repo_test/comment_repo_test.go +++ b/internal/repo/repo_test/comment_repo_test.go @@ -33,7 +33,6 @@ func Test_commentRepo_AddComment(t *testing.T) { err = commentRepo.RemoveComment(context.TODO(), testCommentEntity.ID) assert.NoError(t, err) - return } func Test_commentRepo_GetCommentPage(t *testing.T) { @@ -55,7 +54,6 @@ func Test_commentRepo_GetCommentPage(t *testing.T) { err = commentRepo.RemoveComment(context.TODO(), testCommentEntity.ID) assert.NoError(t, err) - return } func Test_commentRepo_UpdateComment(t *testing.T) { @@ -77,5 +75,4 @@ func Test_commentRepo_UpdateComment(t *testing.T) { err = commentRepo.RemoveComment(context.TODO(), testCommentEntity.ID) assert.NoError(t, err) - return } diff --git a/internal/repo/repo_test/revision_repo_test.go b/internal/repo/repo_test/revision_repo_test.go index fb6e0561..7d82891c 100644 --- a/internal/repo/repo_test/revision_repo_test.go +++ b/internal/repo/repo_test/revision_repo_test.go @@ -3,12 +3,13 @@ package repo_test import ( "context" "encoding/json" + "testing" + "github.com/answerdev/answer/internal/entity" "github.com/answerdev/answer/internal/repo/question" "github.com/answerdev/answer/internal/repo/revision" "github.com/answerdev/answer/internal/repo/unique" "github.com/stretchr/testify/assert" - "testing" ) var q = &entity.Question{ @@ -53,6 +54,7 @@ func Test_revisionRepo_AddRevision(t *testing.T) { assert.NotEqual(t, "", q.ID) content, err := json.Marshal(q) + assert.NoError(t, err) // auto update false rev := getRev(q.ID, q.Title, string(content)) err = revisionRepo.AddRevision(context.TODO(), rev, false) diff --git a/internal/repo/repo_test/tag_repo_test.go b/internal/repo/repo_test/tag_repo_test.go index d7b5e71c..f3e636fb 100644 --- a/internal/repo/repo_test/tag_repo_test.go +++ b/internal/repo/repo_test/tag_repo_test.go @@ -92,7 +92,7 @@ func Test_tagRepo_GetTagListByName(t *testing.T) { tagOnce.Do(addTagList) tagCommonRepo := tag_common.NewTagCommonRepo(testDataSource, unique.NewUniqueIDRepo(testDataSource)) - gotTags, err := tagCommonRepo.GetTagListByName(context.TODO(), testTagList[0].SlugName, 1, false) + gotTags, err := tagCommonRepo.GetTagListByName(context.TODO(), testTagList[0].SlugName, false) assert.NoError(t, err) assert.Equal(t, testTagList[0].SlugName, gotTags[0].SlugName) } diff --git a/internal/repo/repo_test/user_backyard_repo_test.go b/internal/repo/repo_test/user_backyard_repo_test.go index 7fe3be05..de2effda 100644 --- a/internal/repo/repo_test/user_backyard_repo_test.go +++ b/internal/repo/repo_test/user_backyard_repo_test.go @@ -20,7 +20,7 @@ func Test_userBackyardRepo_GetUserInfo(t *testing.T) { func Test_userBackyardRepo_GetUserPage(t *testing.T) { userBackyardRepo := user.NewUserBackyardRepo(testDataSource, auth.NewAuthRepo(testDataSource)) - got, total, err := userBackyardRepo.GetUserPage(context.TODO(), 1, 1, &entity.User{Username: "admin"}, "") + got, total, err := userBackyardRepo.GetUserPage(context.TODO(), 1, 1, &entity.User{Username: "admin"}, "", false) assert.NoError(t, err) assert.Equal(t, int64(1), total) assert.Equal(t, "1", got[0].ID) diff --git a/internal/repo/report/report_repo.go b/internal/repo/report/report_repo.go index 08747246..3fa627f0 100644 --- a/internal/repo/report/report_repo.go +++ b/internal/repo/report/report_repo.go @@ -76,28 +76,27 @@ func (rr *reportRepo) GetReportListPage(ctx context.Context, dto schema.GetRepor } // GetByID get report by ID -func (ar *reportRepo) GetByID(ctx context.Context, id string) (report entity.Report, exist bool, err error) { - report = entity.Report{} - exist, err = ar.data.DB.ID(id).Get(&report) - return -} - -// UpdateByID handle report by ID -func (ar *reportRepo) UpdateByID( - ctx context.Context, - id string, - handleData entity.Report, -) (err error) { - _, err = ar.data.DB.ID(id).Update(&handleData) +func (rr *reportRepo) GetByID(ctx context.Context, id string) (report *entity.Report, exist bool, err error) { + report = &entity.Report{} + exist, err = rr.data.DB.ID(id).Get(report) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } return } -func (vr *reportRepo) GetReportCount(ctx context.Context) (count int64, err error) { +// UpdateByID handle report by ID +func (rr *reportRepo) UpdateByID(ctx context.Context, id string, handleData entity.Report) (err error) { + _, err = rr.data.DB.ID(id).Update(&handleData) + if err != nil { + err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() + } + return +} + +func (rr *reportRepo) GetReportCount(ctx context.Context) (count int64, err error) { list := make([]*entity.Report, 0) - count, err = vr.data.DB.Where("status =?", entity.ReportStatusPending).FindAndCount(&list) + count, err = rr.data.DB.Where("status =?", entity.ReportStatusPending).FindAndCount(&list) if err != nil { return count, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } diff --git a/internal/router/ui_test.go b/internal/router/ui_test.go deleted file mode 100644 index 1ec160e9..00000000 --- a/internal/router/ui_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package router - -import ( - "github.com/gin-gonic/gin" - "github.com/stretchr/testify/assert" - "net/http" - "net/http/httptest" - "testing" -) - -func TestUIRouter_Register(t *testing.T) { - r := gin.Default() - - NewUIRouter().Register(r) - - w := httptest.NewRecorder() - req, _ := http.NewRequest("GET", "/", nil) - - r.ServeHTTP(w, req) - - assert.Equal(t, http.StatusOK, w.Code) -} - -func TestUIRouter_Static(t *testing.T) { - r := gin.Default() - - NewUIRouter().Register(r) - - w := httptest.NewRecorder() - req, _ := http.NewRequest("GET", "/static/version.txt", nil) - - r.ServeHTTP(w, req) - - assert.Equal(t, http.StatusOK, w.Code) - assert.Equal(t, "OK", w.Body.String()) -} diff --git a/internal/service/object_info/object_info.go b/internal/service/object_info/object_info.go index fcf782fb..ab961d26 100644 --- a/internal/service/object_info/object_info.go +++ b/internal/service/object_info/object_info.go @@ -148,6 +148,9 @@ func (os *ObjService) GetInfo(ctx context.Context, objectID string) (objInfo *sc if err != nil { return nil, err } + if !exist { + break + } objInfo = &schema.SimpleObjectInfo{ ObjectID: answerInfo.ID, ObjectCreatorUserID: answerInfo.UserID, diff --git a/internal/service/report_backyard/report_backyard.go b/internal/service/report_backyard/report_backyard.go index 2ab1a595..94335d12 100644 --- a/internal/service/report_backyard/report_backyard.go +++ b/internal/service/report_backyard/report_backyard.go @@ -5,6 +5,7 @@ import ( "github.com/answerdev/answer/internal/service/config" "github.com/answerdev/answer/pkg/htmltext" + "github.com/segmentfault/pacman/log" "github.com/answerdev/answer/internal/base/pager" "github.com/answerdev/answer/internal/base/reason" @@ -106,13 +107,13 @@ func (rs *ReportBackyardService) ListReportPage(ctx context.Context, dto schema. // HandleReported handle the reported object func (rs *ReportBackyardService) HandleReported(ctx context.Context, req schema.ReportHandleReq) (err error) { var ( - reported = entity.Report{} + reported *entity.Report handleData = entity.Report{ FlaggedContent: req.FlaggedContent, FlaggedType: req.FlaggedType, Status: entity.ReportStatusCompleted, } - exist = false + exist bool ) reported, exist, err = rs.reportRepo.GetByID(ctx, req.ID) @@ -159,6 +160,7 @@ func (rs *ReportBackyardService) parseObject(ctx context.Context, resp *[]*schem objIds, err = rs.commonRepo.GetObjectIDMap(r.ObjectID) if err != nil { + log.Error(err) continue } @@ -175,11 +177,19 @@ func (rs *ReportBackyardService) parseObject(ctx context.Context, resp *[]*schem answerId, ok = objIds["answer"] if ok { answer, _, err = rs.answerRepo.GetAnswer(ctx, answerId) + if err != nil { + log.Error(err) + continue + } } commentId, ok = objIds["comment"] if ok { cmt, _, err = rs.commentCommonRepo.GetComment(ctx, commentId) + if err != nil { + log.Error(err) + continue + } } switch r.OType { @@ -208,15 +218,20 @@ func (rs *ReportBackyardService) parseObject(ctx context.Context, resp *[]*schem ReasonType: r.ReportType, } err = rs.configRepo.GetJsonConfigByIDAndSetToObject(r.ReportType, r.Reason) + if err != nil { + log.Error(err) + } } if r.FlaggedType > 0 { r.FlaggedReason = &schema.ReasonItem{ ReasonType: r.FlaggedType, } - _ = rs.configRepo.GetJsonConfigByIDAndSetToObject(r.FlaggedType, r.FlaggedReason) + err = rs.configRepo.GetJsonConfigByIDAndSetToObject(r.FlaggedType, r.FlaggedReason) + if err != nil { + log.Error(err) + } } res[i] = r } - resp = &res } diff --git a/internal/service/report_common/report_common.go b/internal/service/report_common/report_common.go index 1b8c59cc..a467bda4 100644 --- a/internal/service/report_common/report_common.go +++ b/internal/service/report_common/report_common.go @@ -11,7 +11,7 @@ import ( type ReportRepo interface { AddReport(ctx context.Context, report *entity.Report) (err error) GetReportListPage(ctx context.Context, query schema.GetReportListPageDTO) (reports []entity.Report, total int64, err error) - GetByID(ctx context.Context, id string) (report entity.Report, exist bool, err error) + GetByID(ctx context.Context, id string) (report *entity.Report, exist bool, err error) UpdateByID(ctx context.Context, id string, handleData entity.Report) (err error) GetReportCount(ctx context.Context) (count int64, err error) } diff --git a/internal/service/report_handle_backyard/report_handle.go b/internal/service/report_handle_backyard/report_handle.go index 358c2a4c..cbeea25c 100644 --- a/internal/service/report_handle_backyard/report_handle.go +++ b/internal/service/report_handle_backyard/report_handle.go @@ -32,7 +32,7 @@ func NewReportHandle( } // HandleObject this handle object status -func (rh *ReportHandle) HandleObject(ctx context.Context, reported entity.Report, req schema.ReportHandleReq) (err error) { +func (rh *ReportHandle) HandleObject(ctx context.Context, reported *entity.Report, req schema.ReportHandleReq) (err error) { var ( objectID = reported.ObjectID reportedUserID = reported.ReportedUserID diff --git a/internal/service/search_parser/search_parser.go b/internal/service/search_parser/search_parser.go index 781247f7..b3d7492e 100644 --- a/internal/service/search_parser/search_parser.go +++ b/internal/service/search_parser/search_parser.go @@ -318,7 +318,7 @@ func (sp *SearchParser) parseAccepted(query *string) (accepted bool) { if strings.Contains(q, expr) { accepted = true - strings.ReplaceAll(q, expr, "") + q = strings.ReplaceAll(q, expr, "") } *query = strings.TrimSpace(q) diff --git a/internal/service/uploader/upload.go b/internal/service/uploader/upload.go index ffd3824e..3a3df6e8 100644 --- a/internal/service/uploader/upload.go +++ b/internal/service/uploader/upload.go @@ -119,12 +119,14 @@ func (us *UploaderService) AvatarThumbFile(ctx *gin.Context, uploadPath, fileNam return avatarfile, fmt.Errorf("img extension not exist") } err = imaging.Encode(&buf, new_image, FormatExts[fileSuffix]) - if err != nil { return avatarfile, errors.InternalServer(reason.UnknownError).WithError(err).WithStack() } thumbReader := bytes.NewReader(buf.Bytes()) - dir.CreateDirIfNotExist(path.Join(us.serviceConfig.UploadPath, avatarThumbSubPath)) + err = dir.CreateDirIfNotExist(path.Join(us.serviceConfig.UploadPath, avatarThumbSubPath)) + if err != nil { + return nil, errors.InternalServer(reason.UnknownError).WithError(err).WithStack() + } avatarFilePath := path.Join(avatarThumbSubPath, thumbFileName) savefilePath := path.Join(us.serviceConfig.UploadPath, avatarFilePath) out, err := os.Create(savefilePath) diff --git a/internal/service/vote_service.go b/internal/service/vote_service.go index b77fe402..ae555bf0 100644 --- a/internal/service/vote_service.go +++ b/internal/service/vote_service.go @@ -180,6 +180,7 @@ func (vs *VoteService) ListUserVotes(ctx context.Context, req schema.GetVoteWith objInfo, err = vs.objectService.GetInfo(ctx, voteInfo.ObjectID) if err != nil { log.Error(err) + continue } item := schema.GetVoteWithPageResp{ From 05e8ce3a461c9501c6371d01060f1f519fe19480 Mon Sep 17 00:00:00 2001 From: LinkinStar Date: Fri, 16 Dec 2022 16:47:06 +0800 Subject: [PATCH 6/6] fix(robots): Add SEO config initialize data at installation --- internal/migrations/init.go | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/internal/migrations/init.go b/internal/migrations/init.go index 5bbc4631..b90a8196 100644 --- a/internal/migrations/init.go +++ b/internal/migrations/init.go @@ -11,6 +11,23 @@ import ( "xorm.io/xorm" ) +const ( + defaultSEORobotTxt = `User-agent: * +Disallow: /admin +Disallow: /search +Disallow: /install +Disallow: /review +Disallow: /users/login +Disallow: /users/register +Disallow: /users/account-recovery +Disallow: /users/oauth/* +Disallow: /users/*/* +Disallow: /answer/api +Disallow: /*?code* + +Sitemap: ` +) + var tables = []interface{}{ &entity.Activity{}, &entity.Answer{}, @@ -130,6 +147,19 @@ func initSiteInfo(engine *xorm.Engine, language, siteName, siteURL, contactEmail Content: string(loginConfigDataBytes), Status: 1, }) + + seoData := map[string]string{ + "robots": defaultSEORobotTxt + siteURL + "/sitemap.xml", + } + seoDataBytes, _ := json.Marshal(seoData) + _, err = engine.InsertOne(&entity.SiteInfo{ + Type: "seo", + Content: string(seoDataBytes), + Status: 1, + }) + if err != nil { + return err + } return err }