From 1c2151d7108badf2133626331f127f3e34c89ef7 Mon Sep 17 00:00:00 2001 From: LinkinStars Date: Fri, 2 Jun 2023 16:53:04 +0800 Subject: [PATCH] refactor(shortid): remove short id variable --- cmd/wire_gen.go | 11 +-- .../constant/{http_header.go => ctx_flag.go} | 1 + internal/base/constant/site_info.go | 11 +++ internal/base/cron/cron.go | 4 +- internal/base/handler/short_id.go | 16 ++++ internal/base/middleware/auth.go | 6 +- internal/base/middleware/provider.go | 1 + internal/base/middleware/short_id.go | 29 +++++++ internal/base/server/http.go | 3 +- internal/controller/connector_controller.go | 4 +- internal/controller/controller.go | 2 +- internal/controller/lang_controller.go | 4 +- .../plugin_user_center_controller.go | 4 +- internal/controller/question_controller.go | 8 +- internal/controller/siteinfo_controller.go | 16 ++-- internal/controller/template_controller.go | 31 ++++---- .../controller/template_render/controller.go | 6 +- internal/controller/user_controller.go | 4 +- internal/repo/answer/answer_repo.go | 58 +++++++++----- internal/repo/question/question_repo.go | 41 +++++++--- internal/repo/tag/tag_rel_repo.go | 26 +++++-- internal/router/answer_api_router.go | 4 +- internal/router/ui.go | 8 +- internal/schema/siteinfo_schema.go | 24 +++--- internal/service/activity/activity.go | 5 +- .../service/dashboard/dashboard_service.go | 4 +- .../notification/notification_service.go | 21 ++--- internal/service/object_info/object_info.go | 9 ++- internal/service/question_service.go | 19 +++-- internal/service/siteinfo/siteinfo_service.go | 26 ++----- .../siteinfo_common/siteinfo_service.go | 77 +++++++++++-------- internal/service/tag/tag_service.go | 6 +- internal/service/tag_common/tag_common.go | 4 +- internal/service/uploader/upload.go | 4 +- internal/service/user_admin/user_backyard.go | 4 +- internal/service/user_common/user.go | 4 +- .../user_center_login_service.go | 4 +- .../user_external_login_service.go | 4 +- internal/service/user_service.go | 4 +- pkg/uid/sid.go | 13 +--- pkg/uid/sid_test.go | 1 - 41 files changed, 326 insertions(+), 205 deletions(-) rename internal/base/constant/{http_header.go => ctx_flag.go} (62%) create mode 100644 internal/base/handler/short_id.go create mode 100644 internal/base/middleware/short_id.go diff --git a/cmd/wire_gen.go b/cmd/wire_gen.go index 26355097..a074af8d 100644 --- a/cmd/wire_gen.go +++ b/cmd/wire_gen.go @@ -173,7 +173,7 @@ func initApplication(debug bool, serverConf *conf.Server, dbConf *data.Database, answerActivityService := activity2.NewAnswerActivityService(answerActivityRepo, questionActivityRepo) questionService := service.NewQuestionService(questionRepo, tagCommonService, questionCommon, userCommon, userRepo, revisionService, metaService, collectionCommon, answerActivityService, dataData, emailService) answerService := service.NewAnswerService(answerRepo, questionRepo, questionCommon, userCommon, collectionCommon, userRepo, revisionService, answerActivityService, answerCommon, voteRepo, emailService, userRoleRelService) - questionController := controller.NewQuestionController(questionService, answerService, rankService) + questionController := controller.NewQuestionController(questionService, answerService, rankService, siteInfoCommonService) dashboardService := dashboard.NewDashboardService(questionRepo, answerRepo, commentCommonRepo, voteRepo, userRepo, reportRepo, configService, siteInfoCommonService, serviceConf, dataData) answerController := controller.NewAnswerController(answerService, rankService, dashboardService) searchParser := search_parser.NewSearchParser(tagCommonService, userCommon) @@ -195,7 +195,7 @@ func initApplication(debug bool, serverConf *conf.Server, dbConf *data.Database, themeController := controller_admin.NewThemeController() siteInfoService := siteinfo.NewSiteInfoService(siteInfoRepo, siteInfoCommonService, emailService, tagCommonService, configService) siteInfoController := controller_admin.NewSiteInfoController(siteInfoService) - siteinfoController := controller.NewSiteinfoController(siteInfoCommonService) + controllerSiteInfoController := controller.NewSiteInfoController(siteInfoCommonService) notificationRepo := notification.NewNotificationRepo(dataData) notificationCommon := notificationcommon.NewNotificationCommon(dataData, notificationRepo, userCommon, activityRepo, followRepo, objService) notificationService := notification2.NewNotificationService(dataData, notificationRepo, notificationCommon, revisionService) @@ -212,11 +212,12 @@ func initApplication(debug bool, serverConf *conf.Server, dbConf *data.Database, pluginCommonService := plugin_common.NewPluginCommonService(pluginConfigRepo, configService) pluginController := controller_admin.NewPluginController(pluginCommonService) permissionController := controller.NewPermissionController(rankService) - answerAPIRouter := router.NewAnswerAPIRouter(langController, userController, commentController, reportController, voteController, tagController, followController, collectionController, questionController, answerController, searchController, revisionController, rankController, controller_adminReportController, userAdminController, reasonController, themeController, siteInfoController, siteinfoController, notificationController, dashboardController, uploadController, activityController, roleController, pluginController, permissionController) + answerAPIRouter := router.NewAnswerAPIRouter(langController, userController, commentController, reportController, voteController, tagController, followController, collectionController, questionController, answerController, searchController, revisionController, rankController, controller_adminReportController, userAdminController, reasonController, themeController, siteInfoController, controllerSiteInfoController, notificationController, dashboardController, uploadController, activityController, roleController, pluginController, permissionController) swaggerRouter := router.NewSwaggerRouter(swaggerConf) - uiRouter := router.NewUIRouter(siteinfoController, siteInfoCommonService) + uiRouter := router.NewUIRouter(controllerSiteInfoController, siteInfoCommonService) authUserMiddleware := middleware.NewAuthUserMiddleware(authService, siteInfoCommonService) avatarMiddleware := middleware.NewAvatarMiddleware(serviceConf, uploaderService) + shortIDMiddleware := middleware.NewShortIDMiddleware(siteInfoCommonService) templateRenderController := templaterender.NewTemplateRenderController(questionService, userService, tagService, answerService, commentService, dataData, siteInfoCommonService) templateController := controller.NewTemplateController(templateRenderController, siteInfoCommonService) templateRouter := router.NewTemplateRouter(templateController, templateRenderController, siteInfoController) @@ -224,7 +225,7 @@ func initApplication(debug bool, serverConf *conf.Server, dbConf *data.Database, userCenterLoginService := user_external_login2.NewUserCenterLoginService(userRepo, userCommon, userExternalLoginRepo, userActiveActivityRepo, siteInfoCommonService) userCenterController := controller.NewUserCenterController(userCenterLoginService, siteInfoCommonService) pluginAPIRouter := router.NewPluginAPIRouter(connectorController, userCenterController) - ginEngine := server.NewHTTPServer(debug, staticRouter, answerAPIRouter, swaggerRouter, uiRouter, authUserMiddleware, avatarMiddleware, templateRouter, pluginAPIRouter) + ginEngine := server.NewHTTPServer(debug, staticRouter, answerAPIRouter, swaggerRouter, uiRouter, authUserMiddleware, avatarMiddleware, shortIDMiddleware, templateRouter, pluginAPIRouter) scheduledTaskManager := cron.NewScheduledTaskManager(siteInfoCommonService, questionService) application := newApplication(serverConf, ginEngine, scheduledTaskManager) return application, func() { diff --git a/internal/base/constant/http_header.go b/internal/base/constant/ctx_flag.go similarity index 62% rename from internal/base/constant/http_header.go rename to internal/base/constant/ctx_flag.go index a68db8b1..822c1a01 100644 --- a/internal/base/constant/http_header.go +++ b/internal/base/constant/ctx_flag.go @@ -2,4 +2,5 @@ package constant const ( AcceptLanguageFlag = "Accept-Language" + ShortIDFlag = "Short-ID-Enabled" ) diff --git a/internal/base/constant/site_info.go b/internal/base/constant/site_info.go index dfcee76c..d3c4e52a 100644 --- a/internal/base/constant/site_info.go +++ b/internal/base/constant/site_info.go @@ -7,3 +7,14 @@ const ( AvatarTypeGravatar = "gravatar" AvatarTypeCustom = "custom" ) + +const ( + // PermaLinkQuestionIDAndTitle /questions/10010000000000001/post-title + PermaLinkQuestionIDAndTitle = iota + 1 + // PermaLinkQuestionID /questions/10010000000000001 + PermaLinkQuestionID + // PermaLinkQuestionIDAndTitleByShortID /questions/11/post-title + PermaLinkQuestionIDAndTitleByShortID + // PermaLinkQuestionIDByShortID /questions/11 + PermaLinkQuestionIDByShortID +) diff --git a/internal/base/cron/cron.go b/internal/base/cron/cron.go index 79c34597..04f396b0 100644 --- a/internal/base/cron/cron.go +++ b/internal/base/cron/cron.go @@ -12,13 +12,13 @@ import ( // ScheduledTaskManager scheduled task manager type ScheduledTaskManager struct { - siteInfoService *siteinfo_common.SiteInfoCommonService + siteInfoService siteinfo_common.SiteInfoCommonService questionService *service.QuestionService } // NewScheduledTaskManager new scheduled task manager func NewScheduledTaskManager( - siteInfoService *siteinfo_common.SiteInfoCommonService, + siteInfoService siteinfo_common.SiteInfoCommonService, questionService *service.QuestionService, ) *ScheduledTaskManager { manager := &ScheduledTaskManager{ diff --git a/internal/base/handler/short_id.go b/internal/base/handler/short_id.go new file mode 100644 index 00000000..35d62e62 --- /dev/null +++ b/internal/base/handler/short_id.go @@ -0,0 +1,16 @@ +package handler + +import ( + "context" + + "github.com/answerdev/answer/internal/base/constant" +) + +// GetEnableShortID get language from header +func GetEnableShortID(ctx context.Context) bool { + flag, ok := ctx.Value(constant.ShortIDFlag).(bool) + if ok { + return flag + } + return false +} diff --git a/internal/base/middleware/auth.go b/internal/base/middleware/auth.go index ed941c0f..64e59dc1 100644 --- a/internal/base/middleware/auth.go +++ b/internal/base/middleware/auth.go @@ -6,13 +6,13 @@ import ( "github.com/answerdev/answer/internal/schema" "github.com/answerdev/answer/internal/service/role" "github.com/answerdev/answer/internal/service/siteinfo_common" + "github.com/gin-gonic/gin" "github.com/answerdev/answer/internal/base/handler" "github.com/answerdev/answer/internal/base/reason" "github.com/answerdev/answer/internal/entity" "github.com/answerdev/answer/internal/service/auth" "github.com/answerdev/answer/pkg/converter" - "github.com/gin-gonic/gin" "github.com/segmentfault/pacman/errors" ) @@ -21,13 +21,13 @@ var ctxUUIDKey = "ctxUuidKey" // AuthUserMiddleware auth user middleware type AuthUserMiddleware struct { authService *auth.AuthService - siteInfoCommonService *siteinfo_common.SiteInfoCommonService + siteInfoCommonService siteinfo_common.SiteInfoCommonService } // NewAuthUserMiddleware new auth user middleware func NewAuthUserMiddleware( authService *auth.AuthService, - siteInfoCommonService *siteinfo_common.SiteInfoCommonService) *AuthUserMiddleware { + siteInfoCommonService siteinfo_common.SiteInfoCommonService) *AuthUserMiddleware { return &AuthUserMiddleware{ authService: authService, siteInfoCommonService: siteInfoCommonService, diff --git a/internal/base/middleware/provider.go b/internal/base/middleware/provider.go index db89854f..7e699c91 100644 --- a/internal/base/middleware/provider.go +++ b/internal/base/middleware/provider.go @@ -8,4 +8,5 @@ import ( var ProviderSetMiddleware = wire.NewSet( NewAuthUserMiddleware, NewAvatarMiddleware, + NewShortIDMiddleware, ) diff --git a/internal/base/middleware/short_id.go b/internal/base/middleware/short_id.go new file mode 100644 index 00000000..1d1f7f6f --- /dev/null +++ b/internal/base/middleware/short_id.go @@ -0,0 +1,29 @@ +package middleware + +import ( + "github.com/answerdev/answer/internal/base/constant" + "github.com/answerdev/answer/internal/service/siteinfo_common" + "github.com/gin-gonic/gin" + "github.com/segmentfault/pacman/log" +) + +type ShortIDMiddleware struct { + siteInfoService siteinfo_common.SiteInfoCommonService +} + +func NewShortIDMiddleware(siteInfoService siteinfo_common.SiteInfoCommonService) *ShortIDMiddleware { + return &ShortIDMiddleware{ + siteInfoService: siteInfoService, + } +} + +func (sm *ShortIDMiddleware) SetShortIDFlag() gin.HandlerFunc { + return func(ctx *gin.Context) { + siteSeo, err := sm.siteInfoService.GetSiteSeo(ctx) + if err != nil { + log.Error(err) + return + } + ctx.Set(constant.ShortIDFlag, siteSeo.IsShortLink()) + } +} diff --git a/internal/base/server/http.go b/internal/base/server/http.go index 1c79dbee..faa9e046 100644 --- a/internal/base/server/http.go +++ b/internal/base/server/http.go @@ -20,6 +20,7 @@ func NewHTTPServer(debug bool, viewRouter *router.UIRouter, authUserMiddleware *middleware.AuthUserMiddleware, avatarMiddleware *middleware.AvatarMiddleware, + shortIDMiddleware *middleware.ShortIDMiddleware, templateRouter *router.TemplateRouter, pluginAPIRouter *router.PluginAPIRouter, ) *gin.Engine { @@ -30,7 +31,7 @@ func NewHTTPServer(debug bool, gin.SetMode(gin.ReleaseMode) } r := gin.New() - r.Use(brotli.Brotli(brotli.DefaultCompression), middleware.ExtractAndSetAcceptLanguage) + r.Use(brotli.Brotli(brotli.DefaultCompression), middleware.ExtractAndSetAcceptLanguage, shortIDMiddleware.SetShortIDFlag()) r.GET("/healthz", func(ctx *gin.Context) { ctx.String(200, "OK") }) html, _ := fs.Sub(ui.Template, "template") diff --git a/internal/controller/connector_controller.go b/internal/controller/connector_controller.go index f3bfdc5a..f6c35d70 100644 --- a/internal/controller/connector_controller.go +++ b/internal/controller/connector_controller.go @@ -23,14 +23,14 @@ const ( // ConnectorController comment controller type ConnectorController struct { - siteInfoService *siteinfo_common.SiteInfoCommonService + siteInfoService siteinfo_common.SiteInfoCommonService userExternalService *user_external_login.UserExternalLoginService emailService *export.EmailService } // NewConnectorController new controller func NewConnectorController( - siteInfoService *siteinfo_common.SiteInfoCommonService, + siteInfoService siteinfo_common.SiteInfoCommonService, emailService *export.EmailService, userExternalService *user_external_login.UserExternalLoginService, ) *ConnectorController { diff --git a/internal/controller/controller.go b/internal/controller/controller.go index 6b1c2fad..db5f98c7 100644 --- a/internal/controller/controller.go +++ b/internal/controller/controller.go @@ -19,7 +19,7 @@ var ProviderSetController = wire.NewSet( NewRankController, NewReasonController, NewNotificationController, - NewSiteinfoController, + NewSiteInfoController, NewDashboardController, NewUploadController, NewActivityController, diff --git a/internal/controller/lang_controller.go b/internal/controller/lang_controller.go index 0cf2637a..f2717fa8 100644 --- a/internal/controller/lang_controller.go +++ b/internal/controller/lang_controller.go @@ -12,11 +12,11 @@ import ( type LangController struct { translator i18n.Translator - siteInfoService *siteinfo_common.SiteInfoCommonService + siteInfoService siteinfo_common.SiteInfoCommonService } // NewLangController new language controller. -func NewLangController(tr i18n.Translator, siteInfoService *siteinfo_common.SiteInfoCommonService) *LangController { +func NewLangController(tr i18n.Translator, siteInfoService siteinfo_common.SiteInfoCommonService) *LangController { return &LangController{translator: tr, siteInfoService: siteInfoService} } diff --git a/internal/controller/plugin_user_center_controller.go b/internal/controller/plugin_user_center_controller.go index 024a0692..c4476065 100644 --- a/internal/controller/plugin_user_center_controller.go +++ b/internal/controller/plugin_user_center_controller.go @@ -22,13 +22,13 @@ const ( // UserCenterController comment controller type UserCenterController struct { userCenterLoginService *user_external_login.UserCenterLoginService - siteInfoService *siteinfo_common.SiteInfoCommonService + siteInfoService siteinfo_common.SiteInfoCommonService } // NewUserCenterController new controller func NewUserCenterController( userCenterLoginService *user_external_login.UserCenterLoginService, - siteInfoService *siteinfo_common.SiteInfoCommonService, + siteInfoService siteinfo_common.SiteInfoCommonService, ) *UserCenterController { return &UserCenterController{ userCenterLoginService: userCenterLoginService, diff --git a/internal/controller/question_controller.go b/internal/controller/question_controller.go index a0c35be6..29eda5ff 100644 --- a/internal/controller/question_controller.go +++ b/internal/controller/question_controller.go @@ -12,6 +12,7 @@ import ( "github.com/answerdev/answer/internal/service" "github.com/answerdev/answer/internal/service/permission" "github.com/answerdev/answer/internal/service/rank" + "github.com/answerdev/answer/internal/service/siteinfo_common" "github.com/answerdev/answer/pkg/uid" "github.com/gin-gonic/gin" "github.com/jinzhu/copier" @@ -23,6 +24,7 @@ type QuestionController struct { questionService *service.QuestionService answerService *service.AnswerService rankService *rank.RankService + siteInfoService siteinfo_common.SiteInfoCommonService } // NewQuestionController new controller @@ -30,11 +32,13 @@ func NewQuestionController( questionService *service.QuestionService, answerService *service.AnswerService, rankService *rank.RankService, + siteInfoService siteinfo_common.SiteInfoCommonService, ) *QuestionController { return &QuestionController{ questionService: questionService, answerService: answerService, rankService: rankService, + siteInfoService: siteInfoService, } } @@ -220,7 +224,9 @@ func (qc *QuestionController) GetQuestion(ctx *gin.Context) { handler.HandleResponse(ctx, err, nil) return } - info.ID = uid.EnShortID(info.ID) + if handler.GetEnableShortID(ctx) { + info.ID = uid.EnShortID(info.ID) + } handler.HandleResponse(ctx, nil, info) } diff --git a/internal/controller/siteinfo_controller.go b/internal/controller/siteinfo_controller.go index f815bdb9..4cdba56f 100644 --- a/internal/controller/siteinfo_controller.go +++ b/internal/controller/siteinfo_controller.go @@ -11,13 +11,13 @@ import ( "github.com/segmentfault/pacman/log" ) -type SiteinfoController struct { - siteInfoService *siteinfo_common.SiteInfoCommonService +type SiteInfoController struct { + siteInfoService siteinfo_common.SiteInfoCommonService } -// NewSiteinfoController new siteinfo controller. -func NewSiteinfoController(siteInfoService *siteinfo_common.SiteInfoCommonService) *SiteinfoController { - return &SiteinfoController{ +// NewSiteInfoController new site info controller. +func NewSiteInfoController(siteInfoService siteinfo_common.SiteInfoCommonService) *SiteInfoController { + return &SiteInfoController{ siteInfoService: siteInfoService, } } @@ -29,7 +29,7 @@ func NewSiteinfoController(siteInfoService *siteinfo_common.SiteInfoCommonServic // @Produce json // @Success 200 {object} handler.RespBody{data=schema.SiteInfoResp} // @Router /answer/api/v1/siteinfo [get] -func (sc *SiteinfoController) GetSiteInfo(ctx *gin.Context) { +func (sc *SiteInfoController) GetSiteInfo(ctx *gin.Context) { var err error resp := &schema.SiteInfoResp{Version: constant.Version, Revision: constant.Revision} resp.General, err = sc.siteInfoService.GetSiteGeneral(ctx) @@ -80,7 +80,7 @@ func (sc *SiteinfoController) GetSiteInfo(ctx *gin.Context) { // @Produce json // @Success 200 {object} handler.RespBody{data=schema.GetSiteLegalInfoResp} // @Router /answer/api/v1/siteinfo/legal [get] -func (sc *SiteinfoController) GetSiteLegalInfo(ctx *gin.Context) { +func (sc *SiteInfoController) GetSiteLegalInfo(ctx *gin.Context) { req := &schema.GetSiteLegalInfoReq{} if handler.BindAndCheck(ctx, req) { return @@ -102,7 +102,7 @@ func (sc *SiteinfoController) GetSiteLegalInfo(ctx *gin.Context) { } // GetManifestJson get manifest.json -func (sc *SiteinfoController) GetManifestJson(ctx *gin.Context) { +func (sc *SiteInfoController) GetManifestJson(ctx *gin.Context) { favicon := "favicon.ico" resp := &schema.GetManifestJsonResp{ ManifestVersion: 3, diff --git a/internal/controller/template_controller.go b/internal/controller/template_controller.go index cf9dd5ee..ffb53e82 100644 --- a/internal/controller/template_controller.go +++ b/internal/controller/template_controller.go @@ -30,13 +30,13 @@ type TemplateController struct { scriptPath string cssPath string templateRenderController *templaterender.TemplateRenderController - siteInfoService *siteinfo_common.SiteInfoCommonService + siteInfoService siteinfo_common.SiteInfoCommonService } // NewTemplateController new controller func NewTemplateController( templateRenderController *templaterender.TemplateRenderController, - siteInfoService *siteinfo_common.SiteInfoCommonService, + siteInfoService siteinfo_common.SiteInfoCommonService, ) *TemplateController { script, css := GetStyle() return &TemplateController{ @@ -116,7 +116,7 @@ func (tc *TemplateController) Index(ctx *gin.Context) { siteInfo.Canonical = siteInfo.General.SiteUrl UrlUseTitle := false - if siteInfo.SiteSeo.PermaLink == schema.PermaLinkQuestionIDAndTitle { + if siteInfo.SiteSeo.PermaLink == constant.PermaLinkQuestionIDAndTitle { UrlUseTitle = true } siteInfo.Title = "" @@ -149,7 +149,7 @@ func (tc *TemplateController) QuestionList(ctx *gin.Context) { } UrlUseTitle := false - if siteInfo.SiteSeo.PermaLink == schema.PermaLinkQuestionIDAndTitle { + if siteInfo.SiteSeo.PermaLink == constant.PermaLinkQuestionIDAndTitle { UrlUseTitle = true } siteInfo.Title = fmt.Sprintf("Questions - %s", siteInfo.General.Name) @@ -164,16 +164,21 @@ func (tc *TemplateController) QuestionInfoeRdirect(ctx *gin.Context, siteInfo *s id := ctx.Param("id") title := ctx.Param("title") titleIsAnswerID := false - NeedChangeShortID := false + needChangeShortID := false + + siteSeo, err := tc.siteInfoService.GetSiteSeo(ctx) + if err != nil { + return false, "" + } isShortID := uid.IsShortID(id) - if uid.ShortIDSwitch { + if siteSeo.IsShortLink() { if !isShortID { id = uid.EnShortID(id) - NeedChangeShortID = true + needChangeShortID = true } } else { if isShortID { - NeedChangeShortID = true + needChangeShortID = true id = uid.DeShortID(id) } } @@ -186,11 +191,11 @@ func (tc *TemplateController) QuestionInfoeRdirect(ctx *gin.Context, siteInfo *s } siteInfo = tc.SiteInfo(ctx) url = fmt.Sprintf("%s/questions/%s", siteInfo.General.SiteUrl, id) - if siteInfo.SiteSeo.PermaLink == schema.PermaLinkQuestionID || siteInfo.SiteSeo.PermaLink == schema.PermaLinkQuestionIDByShortID { + if siteInfo.SiteSeo.PermaLink == constant.PermaLinkQuestionID || siteInfo.SiteSeo.PermaLink == constant.PermaLinkQuestionIDByShortID { if len(ctx.Request.URL.Query()) > 0 { url = fmt.Sprintf("%s?%s", url, ctx.Request.URL.RawQuery) } - if NeedChangeShortID { + if needChangeShortID { return true, url } //not have title @@ -216,7 +221,7 @@ func (tc *TemplateController) QuestionInfoeRdirect(ctx *gin.Context, siteInfo *s } //have title if len(title) > 0 && !titleIsAnswerID && correctTitle { - if NeedChangeShortID { + if needChangeShortID { return true, url } return false, "" @@ -287,7 +292,7 @@ func (tc *TemplateController) QuestionInfo(ctx *gin.Context) { return } siteInfo.Canonical = fmt.Sprintf("%s/questions/%s/%s", siteInfo.General.SiteUrl, id, encodeTitle) - if siteInfo.SiteSeo.PermaLink == schema.PermaLinkQuestionID { + if siteInfo.SiteSeo.PermaLink == constant.PermaLinkQuestionID { siteInfo.Canonical = fmt.Sprintf("%s/questions/%s", siteInfo.General.SiteUrl, id) } jsonLD := &schema.QAPageJsonLD{} @@ -402,7 +407,7 @@ func (tc *TemplateController) TagInfo(ctx *gin.Context) { siteInfo.Keywords = taginifo.DisplayName UrlUseTitle := false - if siteInfo.SiteSeo.PermaLink == schema.PermaLinkQuestionIDAndTitle { + if siteInfo.SiteSeo.PermaLink == constant.PermaLinkQuestionIDAndTitle { UrlUseTitle = true } siteInfo.Title = fmt.Sprintf("'%s' Questions - %s", taginifo.DisplayName, siteInfo.General.Name) diff --git a/internal/controller/template_render/controller.go b/internal/controller/template_render/controller.go index f44c1ea6..8a852132 100644 --- a/internal/controller/template_render/controller.go +++ b/internal/controller/template_render/controller.go @@ -6,11 +6,11 @@ import ( "github.com/answerdev/answer/internal/base/data" "github.com/answerdev/answer/internal/service/comment" "github.com/answerdev/answer/internal/service/siteinfo_common" + "github.com/google/wire" "github.com/answerdev/answer/internal/schema" "github.com/answerdev/answer/internal/service" "github.com/answerdev/answer/internal/service/tag" - "github.com/google/wire" ) // ProviderSetTemplateRenderController is template render controller providers. @@ -25,7 +25,7 @@ type TemplateRenderController struct { answerService *service.AnswerService commentService *comment.CommentService data *data.Data - siteInfoService *siteinfo_common.SiteInfoCommonService + siteInfoService siteinfo_common.SiteInfoCommonService } func NewTemplateRenderController( @@ -35,7 +35,7 @@ func NewTemplateRenderController( answerService *service.AnswerService, commentService *comment.CommentService, data *data.Data, - siteInfoService *siteinfo_common.SiteInfoCommonService, + siteInfoService siteinfo_common.SiteInfoCommonService, ) *TemplateRenderController { return &TemplateRenderController{ diff --git a/internal/controller/user_controller.go b/internal/controller/user_controller.go index 51fbc4ea..42d61e1d 100644 --- a/internal/controller/user_controller.go +++ b/internal/controller/user_controller.go @@ -26,7 +26,7 @@ type UserController struct { actionService *action.CaptchaService uploaderService uploader.UploaderService emailService *export.EmailService - siteInfoCommonService *siteinfo_common.SiteInfoCommonService + siteInfoCommonService siteinfo_common.SiteInfoCommonService } // NewUserController new controller @@ -36,7 +36,7 @@ func NewUserController( actionService *action.CaptchaService, emailService *export.EmailService, uploaderService uploader.UploaderService, - siteInfoCommonService *siteinfo_common.SiteInfoCommonService, + siteInfoCommonService siteinfo_common.SiteInfoCommonService, ) *UserController { return &UserController{ authService: authService, diff --git a/internal/repo/answer/answer_repo.go b/internal/repo/answer/answer_repo.go index 77b76779..aa8b42f6 100644 --- a/internal/repo/answer/answer_repo.go +++ b/internal/repo/answer/answer_repo.go @@ -6,6 +6,7 @@ import ( "time" "unicode" + "github.com/answerdev/answer/internal/base/handler" "xorm.io/builder" "github.com/answerdev/answer/internal/base/constant" @@ -58,8 +59,10 @@ func (ar *answerRepo) AddAnswer(ctx context.Context, answer *entity.Answer) (err if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } - answer.ID = uid.EnShortID(answer.ID) - answer.QuestionID = uid.EnShortID(answer.QuestionID) + if handler.GetEnableShortID(ctx) { + answer.ID = uid.EnShortID(answer.ID) + answer.QuestionID = uid.EnShortID(answer.QuestionID) + } return nil } @@ -109,9 +112,10 @@ func (ar *answerRepo) GetAnswer(ctx context.Context, id string) ( if err != nil { return nil, false, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } - answer.ID = uid.EnShortID(answer.ID) - answer.QuestionID = uid.EnShortID(answer.QuestionID) - + if handler.GetEnableShortID(ctx) { + answer.ID = uid.EnShortID(answer.ID) + answer.QuestionID = uid.EnShortID(answer.QuestionID) + } return } @@ -134,9 +138,11 @@ func (ar *answerRepo) GetAnswerList(ctx context.Context, answer *entity.Answer) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } - for _, item := range answerList { - item.ID = uid.EnShortID(item.ID) - item.QuestionID = uid.EnShortID(item.QuestionID) + if handler.GetEnableShortID(ctx) { + for _, item := range answerList { + item.ID = uid.EnShortID(item.ID) + item.QuestionID = uid.EnShortID(item.QuestionID) + } } return } @@ -150,9 +156,11 @@ func (ar *answerRepo) GetAnswerPage(ctx context.Context, page, pageSize int, ans if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } - for _, item := range answerList { - item.ID = uid.EnShortID(item.ID) - item.QuestionID = uid.EnShortID(item.QuestionID) + if handler.GetEnableShortID(ctx) { + for _, item := range answerList { + item.ID = uid.EnShortID(item.ID) + item.QuestionID = uid.EnShortID(item.QuestionID) + } } return } @@ -191,8 +199,10 @@ func (ar *answerRepo) GetByID(ctx context.Context, id string) (*entity.Answer, b if err != nil { return &resp, false, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } - resp.ID = uid.EnShortID(resp.ID) - resp.QuestionID = uid.EnShortID(resp.QuestionID) + if handler.GetEnableShortID(ctx) { + resp.ID = uid.EnShortID(resp.ID) + resp.QuestionID = uid.EnShortID(resp.QuestionID) + } return &resp, has, nil } @@ -203,8 +213,10 @@ func (ar *answerRepo) GetByUserIDQuestionID(ctx context.Context, userID string, if err != nil { return &resp, false, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } - resp.ID = uid.EnShortID(resp.ID) - resp.QuestionID = uid.EnShortID(resp.QuestionID) + if handler.GetEnableShortID(ctx) { + resp.ID = uid.EnShortID(resp.ID) + resp.QuestionID = uid.EnShortID(resp.QuestionID) + } return &resp, has, nil } @@ -251,9 +263,11 @@ func (ar *answerRepo) SearchList(ctx context.Context, search *entity.AnswerSearc if err != nil { return rows, count, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } - for _, item := range rows { - item.ID = uid.EnShortID(item.ID) - item.QuestionID = uid.EnShortID(item.QuestionID) + if handler.GetEnableShortID(ctx) { + for _, item := range rows { + item.ID = uid.EnShortID(item.ID) + item.QuestionID = uid.EnShortID(item.QuestionID) + } } return rows, count, nil } @@ -329,9 +343,11 @@ func (ar *answerRepo) AdminSearchList(ctx context.Context, search *entity.AdminA if err != nil { return rows, count, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } - for _, item := range rows { - item.ID = uid.EnShortID(item.ID) - item.QuestionID = uid.EnShortID(item.QuestionID) + if handler.GetEnableShortID(ctx) { + for _, item := range rows { + item.ID = uid.EnShortID(item.ID) + item.QuestionID = uid.EnShortID(item.QuestionID) + } } return rows, count, nil } diff --git a/internal/repo/question/question_repo.go b/internal/repo/question/question_repo.go index 01dd98e4..06bfdf72 100644 --- a/internal/repo/question/question_repo.go +++ b/internal/repo/question/question_repo.go @@ -7,6 +7,7 @@ import ( "time" "unicode" + "github.com/answerdev/answer/internal/base/handler" "xorm.io/builder" "github.com/answerdev/answer/internal/base/constant" @@ -50,7 +51,9 @@ func (qr *questionRepo) AddQuestion(ctx context.Context, question *entity.Questi if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } - question.ID = uid.EnShortID(question.ID) + if handler.GetEnableShortID(ctx) { + question.ID = uid.EnShortID(question.ID) + } return } @@ -71,7 +74,9 @@ func (qr *questionRepo) UpdateQuestion(ctx context.Context, question *entity.Que if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } - question.ID = uid.EnShortID(question.ID) + if handler.GetEnableShortID(ctx) { + question.ID = uid.EnShortID(question.ID) + } return } @@ -163,7 +168,9 @@ func (qr *questionRepo) GetQuestion(ctx context.Context, id string) ( if err != nil { return nil, false, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } - question.ID = uid.EnShortID(question.ID) + if handler.GetEnableShortID(ctx) { + question.ID = uid.EnShortID(question.ID) + } return } @@ -174,8 +181,10 @@ func (qr *questionRepo) SearchByTitleLike(ctx context.Context, title string) (qu if err != nil { return nil, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } - for _, item := range questionList { - item.ID = uid.EnShortID(item.ID) + if handler.GetEnableShortID(ctx) { + for _, item := range questionList { + item.ID = uid.EnShortID(item.ID) + } } return } @@ -189,8 +198,10 @@ func (qr *questionRepo) FindByID(ctx context.Context, id []string) (questionList if err != nil { return nil, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } - for _, item := range questionList { - item.ID = uid.EnShortID(item.ID) + if handler.GetEnableShortID(ctx) { + for _, item := range questionList { + item.ID = uid.EnShortID(item.ID) + } } return } @@ -260,7 +271,9 @@ func (qr *questionRepo) GetQuestionIDsPage(ctx context.Context, page, pageSize i } for _, question := range rows { item := &schema.SiteMapQuestionInfo{} - item.ID = uid.EnShortID(question.ID) + if handler.GetEnableShortID(ctx) { + item.ID = uid.EnShortID(question.ID) + } item.Title = htmltext.UrlTitle(question.Title) updateTime := fmt.Sprintf("%v", question.PostUpdateTime.Format(time.RFC3339)) if question.PostUpdateTime.Unix() < 1 { @@ -311,8 +324,10 @@ func (qr *questionRepo) GetQuestionPage(ctx context.Context, page, pageSize int, if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } - for _, item := range questionList { - item.ID = uid.EnShortID(item.ID) + if handler.GetEnableShortID(ctx) { + for _, item := range questionList { + item.ID = uid.EnShortID(item.ID) + } } return questionList, total, err } @@ -378,8 +393,10 @@ func (qr *questionRepo) AdminSearchList(ctx context.Context, search *schema.Admi err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() return rows, count, err } - for _, item := range rows { - item.ID = uid.EnShortID(item.ID) + if handler.GetEnableShortID(ctx) { + for _, item := range rows { + item.ID = uid.EnShortID(item.ID) + } } return rows, count, nil } diff --git a/internal/repo/tag/tag_rel_repo.go b/internal/repo/tag/tag_rel_repo.go index 62b3fe7a..33fbe08f 100644 --- a/internal/repo/tag/tag_rel_repo.go +++ b/internal/repo/tag/tag_rel_repo.go @@ -4,6 +4,7 @@ import ( "context" "github.com/answerdev/answer/internal/base/data" + "github.com/answerdev/answer/internal/base/handler" "github.com/answerdev/answer/internal/base/reason" "github.com/answerdev/answer/internal/entity" tagcommon "github.com/answerdev/answer/internal/service/tag_common" @@ -36,8 +37,10 @@ func (tr *tagRelRepo) AddTagRelList(ctx context.Context, tagList []*entity.TagRe if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } - for _, item := range tagList { - item.ObjectID = uid.EnShortID(item.ObjectID) + if handler.GetEnableShortID(ctx) { + for _, item := range tagList { + item.ObjectID = uid.EnShortID(item.ObjectID) + } } return } @@ -89,8 +92,11 @@ func (tr *tagRelRepo) GetObjectTagRelWithoutStatus(ctx context.Context, objectID exist, err = session.Get(tagRel) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() + return + } + if handler.GetEnableShortID(ctx) { + tagRel.ObjectID = uid.EnShortID(tagRel.ObjectID) } - tagRel.ObjectID = uid.EnShortID(tagRel.ObjectID) return } @@ -112,9 +118,12 @@ func (tr *tagRelRepo) GetObjectTagRelList(ctx context.Context, objectID string) err = session.Find(&tagListList) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() + return } - for _, item := range tagListList { - item.ObjectID = uid.EnShortID(item.ObjectID) + if handler.GetEnableShortID(ctx) { + for _, item := range tagListList { + item.ObjectID = uid.EnShortID(item.ObjectID) + } } return } @@ -130,9 +139,12 @@ func (tr *tagRelRepo) BatchGetObjectTagRelList(ctx context.Context, objectIds [] err = session.Find(&tagListList) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() + return } - for _, item := range tagListList { - item.ObjectID = uid.EnShortID(item.ObjectID) + if handler.GetEnableShortID(ctx) { + for _, item := range tagListList { + item.ObjectID = uid.EnShortID(item.ObjectID) + } } return } diff --git a/internal/router/answer_api_router.go b/internal/router/answer_api_router.go index 025ee594..5aaebb86 100644 --- a/internal/router/answer_api_router.go +++ b/internal/router/answer_api_router.go @@ -26,7 +26,7 @@ type AnswerAPIRouter struct { reasonController *controller.ReasonController themeController *controller_admin.ThemeController siteInfoController *controller_admin.SiteInfoController - siteinfoController *controller.SiteinfoController + siteinfoController *controller.SiteInfoController notificationController *controller.NotificationController dashboardController *controller.DashboardController uploadController *controller.UploadController @@ -55,7 +55,7 @@ func NewAnswerAPIRouter( reasonController *controller.ReasonController, themeController *controller_admin.ThemeController, siteInfoController *controller_admin.SiteInfoController, - siteinfoController *controller.SiteinfoController, + siteinfoController *controller.SiteInfoController, notificationController *controller.NotificationController, dashboardController *controller.DashboardController, uploadController *controller.UploadController, diff --git a/internal/router/ui.go b/internal/router/ui.go index f94bcd3f..1e8bf8ec 100644 --- a/internal/router/ui.go +++ b/internal/router/ui.go @@ -21,14 +21,14 @@ const UIStaticPath = "build/static" // UIRouter is an interface that provides ui static file routers type UIRouter struct { - siteInfoController *controller.SiteinfoController - siteInfoService *siteinfo_common.SiteInfoCommonService + siteInfoController *controller.SiteInfoController + siteInfoService siteinfo_common.SiteInfoCommonService } // NewUIRouter creates a new UIRouter instance with the embed resources func NewUIRouter( - siteInfoController *controller.SiteinfoController, - siteInfoService *siteinfo_common.SiteInfoCommonService, + siteInfoController *controller.SiteInfoController, + siteInfoService siteinfo_common.SiteInfoCommonService, ) *UIRouter { return &UIRouter{ siteInfoController: siteInfoController, diff --git a/internal/schema/siteinfo_schema.go b/internal/schema/siteinfo_schema.go index 119420cf..bef9cf8e 100644 --- a/internal/schema/siteinfo_schema.go +++ b/internal/schema/siteinfo_schema.go @@ -14,11 +14,6 @@ import ( "github.com/segmentfault/pacman/errors" ) -const PermaLinkQuestionIDAndTitle = 1 // /questions/10010000000000001/post-title -const PermaLinkQuestionID = 2 // /questions/10010000000000001 -const PermaLinkQuestionIDAndTitleByShortID = 3 // /questions/11/post-title -const PermaLinkQuestionIDByShortID = 4 // /questions/11 - // SiteGeneralReq site general request type SiteGeneralReq struct { Name string `validate:"required,sanitizer,gt=1,lte=128" form:"name" json:"name"` @@ -28,11 +23,6 @@ type SiteGeneralReq struct { ContactEmail string `validate:"required,sanitizer,gt=1,lte=512,email" form:"contact_email" json:"contact_email"` } -type SiteSeoReq struct { - PermaLink int `validate:"required,lte=4,gte=0" form:"permalink" json:"permalink"` - Robots string `validate:"required" form:"robots" json:"robots"` -} - func (r *SiteGeneralReq) FormatSiteUrl() { parsedUrl, err := url.Parse(r.SiteUrl) if err != nil { @@ -127,6 +117,16 @@ type SiteThemeReq struct { ThemeConfig map[string]interface{} `validate:"omitempty" json:"theme_config"` } +type SiteSeoReq struct { + PermaLink int `validate:"required,lte=4,gte=0" form:"permalink" json:"permalink"` + Robots string `validate:"required" form:"robots" json:"robots"` +} + +func (s *SiteSeoResp) IsShortLink() bool { + return s.PermaLink == constant.PermaLinkQuestionIDAndTitleByShortID || + s.PermaLink == constant.PermaLinkQuestionIDByShortID +} + // SiteGeneralResp site general response type SiteGeneralResp SiteGeneralReq @@ -186,7 +186,7 @@ type SiteInfoResp struct { Login *SiteLoginResp `json:"login"` Theme *SiteThemeResp `json:"theme"` CustomCssHtml *SiteCustomCssHTMLResp `json:"custom_css_html"` - SiteSeo *SiteSeoReq `json:"site_seo"` + SiteSeo *SiteSeoResp `json:"site_seo"` SiteUsers *SiteUsersResp `json:"site_users"` Version string `json:"version"` Revision string `json:"revision"` @@ -195,7 +195,7 @@ type TemplateSiteInfoResp struct { General *SiteGeneralResp `json:"general"` Interface *SiteInterfaceResp `json:"interface"` Branding *SiteBrandingResp `json:"branding"` - SiteSeo *SiteSeoReq `json:"site_seo"` + SiteSeo *SiteSeoResp `json:"site_seo"` CustomCssHtml *SiteCustomCssHTMLResp `json:"custom_css_html"` Title string Year string diff --git a/internal/service/activity/activity.go b/internal/service/activity/activity.go index ebd5e6df..6c491f25 100644 --- a/internal/service/activity/activity.go +++ b/internal/service/activity/activity.go @@ -7,6 +7,7 @@ import ( "strings" "github.com/answerdev/answer/internal/base/constant" + "github.com/answerdev/answer/internal/base/handler" "github.com/answerdev/answer/internal/entity" "github.com/answerdev/answer/internal/schema" "github.com/answerdev/answer/internal/service/activity_common" @@ -97,7 +98,9 @@ func (as *ActivityService) GetObjectTimeline(ctx context.Context, req *schema.Ge } if item.ObjectType == constant.QuestionObjectType || item.ObjectType == constant.AnswerObjectType { - item.ObjectID = uid.EnShortID(act.ObjectID) + if handler.GetEnableShortID(ctx) { + item.ObjectID = uid.EnShortID(act.ObjectID) + } } cfg, err := as.configService.GetConfigByID(ctx, act.ActivityType) diff --git a/internal/service/dashboard/dashboard_service.go b/internal/service/dashboard/dashboard_service.go index fa798e69..a74e4f86 100644 --- a/internal/service/dashboard/dashboard_service.go +++ b/internal/service/dashboard/dashboard_service.go @@ -36,7 +36,7 @@ type DashboardService struct { userRepo usercommon.UserRepo reportRepo report_common.ReportRepo configService *config.ConfigService - siteInfoService *siteinfo_common.SiteInfoCommonService + siteInfoService siteinfo_common.SiteInfoCommonService serviceConfig *service_config.ServiceConfig data *data.Data @@ -50,7 +50,7 @@ func NewDashboardService( userRepo usercommon.UserRepo, reportRepo report_common.ReportRepo, configService *config.ConfigService, - siteInfoService *siteinfo_common.SiteInfoCommonService, + siteInfoService siteinfo_common.SiteInfoCommonService, serviceConfig *service_config.ServiceConfig, data *data.Data, diff --git a/internal/service/notification/notification_service.go b/internal/service/notification/notification_service.go index 6e7d09d6..25d8444e 100644 --- a/internal/service/notification/notification_service.go +++ b/internal/service/notification/notification_service.go @@ -146,6 +146,7 @@ func (ns *NotificationService) GetNotificationPage(ctx context.Context, searchCo func (ns *NotificationService) formatNotificationPage(ctx context.Context, notifications []*entity.Notification) ( resp []*schema.NotificationContent, err error) { lang := handler.GetLangByCtx(ctx) + enableShortID := handler.GetEnableShortID(ctx) for _, notificationInfo := range notifications { item := &schema.NotificationContent{} if err := json.Unmarshal([]byte(notificationInfo.Content), item); err != nil { @@ -163,17 +164,19 @@ func (ns *NotificationService) formatNotificationPage(ctx context.Context, notif item.UpdateTime = notificationInfo.UpdatedAt.Unix() item.IsRead = notificationInfo.IsRead == schema.NotificationRead - if answerID, ok := item.ObjectInfo.ObjectMap["answer"]; ok { - if item.ObjectInfo.ObjectID == answerID { - item.ObjectInfo.ObjectID = uid.EnShortID(item.ObjectInfo.ObjectMap["answer"]) + if enableShortID { + if answerID, ok := item.ObjectInfo.ObjectMap["answer"]; ok { + if item.ObjectInfo.ObjectID == answerID { + item.ObjectInfo.ObjectID = uid.EnShortID(item.ObjectInfo.ObjectMap["answer"]) + } + item.ObjectInfo.ObjectMap["answer"] = uid.EnShortID(item.ObjectInfo.ObjectMap["answer"]) } - item.ObjectInfo.ObjectMap["answer"] = uid.EnShortID(item.ObjectInfo.ObjectMap["answer"]) - } - if questionID, ok := item.ObjectInfo.ObjectMap["question"]; ok { - if item.ObjectInfo.ObjectID == questionID { - item.ObjectInfo.ObjectID = uid.EnShortID(item.ObjectInfo.ObjectMap["question"]) + if questionID, ok := item.ObjectInfo.ObjectMap["question"]; ok { + if item.ObjectInfo.ObjectID == questionID { + item.ObjectInfo.ObjectID = uid.EnShortID(item.ObjectInfo.ObjectMap["question"]) + } + item.ObjectInfo.ObjectMap["question"] = uid.EnShortID(item.ObjectInfo.ObjectMap["question"]) } - item.ObjectInfo.ObjectMap["question"] = uid.EnShortID(item.ObjectInfo.ObjectMap["question"]) } resp = append(resp, item) diff --git a/internal/service/object_info/object_info.go b/internal/service/object_info/object_info.go index feda14f9..09e59882 100644 --- a/internal/service/object_info/object_info.go +++ b/internal/service/object_info/object_info.go @@ -4,6 +4,7 @@ import ( "context" "github.com/answerdev/answer/internal/base/constant" + "github.com/answerdev/answer/internal/base/handler" "github.com/answerdev/answer/internal/base/reason" "github.com/answerdev/answer/internal/schema" answercommon "github.com/answerdev/answer/internal/service/answer_common" @@ -51,7 +52,9 @@ func (os *ObjService) GetUnreviewedRevisionInfo(ctx context.Context, objectID st if err != nil { return nil, err } - questionInfo.ID = uid.EnShortID(questionInfo.ID) + if handler.GetEnableShortID(ctx) { + questionInfo.ID = uid.EnShortID(questionInfo.ID) + } if !exist { break } @@ -87,7 +90,9 @@ func (os *ObjService) GetUnreviewedRevisionInfo(ctx context.Context, objectID st if !exist { break } - questionInfo.ID = uid.EnShortID(questionInfo.ID) + if handler.GetEnableShortID(ctx) { + questionInfo.ID = uid.EnShortID(questionInfo.ID) + } objInfo = &schema.UnreviewedRevisionInfoInfo{ ObjectID: answerInfo.ID, Title: questionInfo.Title, diff --git a/internal/service/question_service.go b/internal/service/question_service.go index 5e138428..848e2d54 100644 --- a/internal/service/question_service.go +++ b/internal/service/question_service.go @@ -1018,16 +1018,19 @@ func (qs *QuestionService) PersonalCollectionPage(ctx context.Context, req *sche return nil, err } for _, id := range questionIDs { - _, ok := questionMaps[uid.EnShortID(id)] + if handler.GetEnableShortID(ctx) { + id = uid.EnShortID(id) + } + _, ok := questionMaps[id] if ok { - questionMaps[uid.EnShortID(id)].LastAnsweredUserInfo = nil - questionMaps[uid.EnShortID(id)].UpdateUserInfo = nil - questionMaps[uid.EnShortID(id)].Content = "" - questionMaps[uid.EnShortID(id)].HTML = "" - if questionMaps[uid.EnShortID(id)].Status == entity.QuestionStatusDeleted { - questionMaps[uid.EnShortID(id)].Title = "Deleted question" + questionMaps[id].LastAnsweredUserInfo = nil + questionMaps[id].UpdateUserInfo = nil + questionMaps[id].Content = "" + questionMaps[id].HTML = "" + if questionMaps[id].Status == entity.QuestionStatusDeleted { + questionMaps[id].Title = "Deleted question" } - list = append(list, questionMaps[uid.EnShortID(id)]) + list = append(list, questionMaps[id]) } } diff --git a/internal/service/siteinfo/siteinfo_service.go b/internal/service/siteinfo/siteinfo_service.go index 0778bbbd..db21b550 100644 --- a/internal/service/siteinfo/siteinfo_service.go +++ b/internal/service/siteinfo/siteinfo_service.go @@ -15,7 +15,6 @@ import ( "github.com/answerdev/answer/internal/service/export" "github.com/answerdev/answer/internal/service/siteinfo_common" tagcommon "github.com/answerdev/answer/internal/service/tag_common" - "github.com/answerdev/answer/pkg/uid" "github.com/answerdev/answer/plugin" "github.com/jinzhu/copier" "github.com/segmentfault/pacman/errors" @@ -24,7 +23,7 @@ import ( type SiteInfoService struct { siteInfoRepo siteinfo_common.SiteInfoRepo - siteInfoCommonService *siteinfo_common.SiteInfoCommonService + siteInfoCommonService siteinfo_common.SiteInfoCommonService emailService *export.EmailService tagCommonService *tagcommon.TagCommonService configService *config.ConfigService @@ -32,7 +31,7 @@ type SiteInfoService struct { func NewSiteInfoService( siteInfoRepo siteinfo_common.SiteInfoRepo, - siteInfoCommonService *siteinfo_common.SiteInfoCommonService, + siteInfoCommonService siteinfo_common.SiteInfoCommonService, emailService *export.EmailService, tagCommonService *tagcommon.TagCommonService, configService *config.ConfigService, @@ -280,27 +279,12 @@ func (s *SiteInfoService) GetSeo(ctx context.Context) (resp *schema.SiteSeoReq, } func (s *SiteInfoService) SaveSeo(ctx context.Context, req schema.SiteSeoReq) (err error) { - var ( - siteType = constant.SiteTypeSeo - content []byte - ) - content, _ = json.Marshal(req) - + content, _ := json.Marshal(req) data := entity.SiteInfo{ - Type: siteType, + Type: constant.SiteTypeSeo, Content: string(content), } - - err = s.siteInfoRepo.SaveByType(ctx, siteType, &data) - if err != nil { - return - } - if req.PermaLink == schema.PermaLinkQuestionIDAndTitleByShortID || req.PermaLink == schema.PermaLinkQuestionIDByShortID { - uid.ShortIDSwitch = true - } else { - uid.ShortIDSwitch = false - } - return + return s.siteInfoRepo.SaveByType(ctx, constant.SiteTypeSeo, &data) } func (s *SiteInfoService) GetPrivilegesConfig(ctx context.Context) (resp *schema.GetPrivilegesConfigResp, err error) { diff --git a/internal/service/siteinfo_common/siteinfo_service.go b/internal/service/siteinfo_common/siteinfo_service.go index fff82a8d..2ccd7e86 100644 --- a/internal/service/siteinfo_common/siteinfo_service.go +++ b/internal/service/siteinfo_common/siteinfo_service.go @@ -8,7 +8,6 @@ import ( "github.com/answerdev/answer/internal/entity" "github.com/answerdev/answer/internal/schema" "github.com/answerdev/answer/pkg/gravatar" - "github.com/answerdev/answer/pkg/uid" "github.com/segmentfault/pacman/log" ) @@ -18,31 +17,36 @@ type SiteInfoRepo interface { GetByType(ctx context.Context, siteType string) (siteInfo *entity.SiteInfo, exist bool, err error) } -// SiteInfoCommonService site info common service -type SiteInfoCommonService struct { +// siteInfoCommonService site info common service +type siteInfoCommonService struct { siteInfoRepo SiteInfoRepo } +type SiteInfoCommonService interface { + GetSiteGeneral(ctx context.Context) (resp *schema.SiteGeneralResp, err error) + GetSiteInterface(ctx context.Context) (resp *schema.SiteInterfaceResp, err error) + GetSiteBranding(ctx context.Context) (resp *schema.SiteBrandingResp, err error) + GetSiteUsers(ctx context.Context) (resp *schema.SiteUsersResp, err error) + FormatAvatar(ctx context.Context, originalAvatarData, email string) *schema.AvatarInfo + FormatListAvatar(ctx context.Context, userList []*entity.User) (userID2AvatarMapping map[string]*schema.AvatarInfo) + GetSiteWrite(ctx context.Context) (resp *schema.SiteWriteResp, err error) + GetSiteLegal(ctx context.Context) (resp *schema.SiteLegalResp, err error) + GetSiteLogin(ctx context.Context) (resp *schema.SiteLoginResp, err error) + GetSiteCustomCssHTML(ctx context.Context) (resp *schema.SiteCustomCssHTMLResp, err error) + GetSiteTheme(ctx context.Context) (resp *schema.SiteThemeResp, err error) + GetSiteSeo(ctx context.Context) (resp *schema.SiteSeoResp, err error) + GetSiteInfoByType(ctx context.Context, siteType string, resp interface{}) (err error) +} + // NewSiteInfoCommonService new site info common service -func NewSiteInfoCommonService(siteInfoRepo SiteInfoRepo) *SiteInfoCommonService { - siteInfo := &SiteInfoCommonService{ +func NewSiteInfoCommonService(siteInfoRepo SiteInfoRepo) SiteInfoCommonService { + return &siteInfoCommonService{ siteInfoRepo: siteInfoRepo, } - seoinfo, err := siteInfo.GetSiteSeo(context.Background()) - if err != nil { - log.Error("seoinfo error", err) - } - if seoinfo.PermaLink == schema.PermaLinkQuestionIDAndTitleByShortID || seoinfo.PermaLink == schema.PermaLinkQuestionIDByShortID { - uid.ShortIDSwitch = true - } else { - uid.ShortIDSwitch = false - } - - return siteInfo } // GetSiteGeneral get site info general -func (s *SiteInfoCommonService) GetSiteGeneral(ctx context.Context) (resp *schema.SiteGeneralResp, err error) { +func (s *siteInfoCommonService) GetSiteGeneral(ctx context.Context) (resp *schema.SiteGeneralResp, err error) { resp = &schema.SiteGeneralResp{} if err = s.GetSiteInfoByType(ctx, constant.SiteTypeGeneral, resp); err != nil { return nil, err @@ -51,7 +55,7 @@ func (s *SiteInfoCommonService) GetSiteGeneral(ctx context.Context) (resp *schem } // GetSiteInterface get site info interface -func (s *SiteInfoCommonService) GetSiteInterface(ctx context.Context) (resp *schema.SiteInterfaceResp, err error) { +func (s *siteInfoCommonService) GetSiteInterface(ctx context.Context) (resp *schema.SiteInterfaceResp, err error) { resp = &schema.SiteInterfaceResp{} if err = s.GetSiteInfoByType(ctx, constant.SiteTypeInterface, resp); err != nil { return nil, err @@ -60,7 +64,7 @@ func (s *SiteInfoCommonService) GetSiteInterface(ctx context.Context) (resp *sch } // GetSiteBranding get site info branding -func (s *SiteInfoCommonService) GetSiteBranding(ctx context.Context) (resp *schema.SiteBrandingResp, err error) { +func (s *siteInfoCommonService) GetSiteBranding(ctx context.Context) (resp *schema.SiteBrandingResp, err error) { resp = &schema.SiteBrandingResp{} if err = s.GetSiteInfoByType(ctx, constant.SiteTypeBranding, resp); err != nil { return nil, err @@ -69,7 +73,7 @@ func (s *SiteInfoCommonService) GetSiteBranding(ctx context.Context) (resp *sche } // GetSiteUsers get site info about users -func (s *SiteInfoCommonService) GetSiteUsers(ctx context.Context) (resp *schema.SiteUsersResp, err error) { +func (s *siteInfoCommonService) GetSiteUsers(ctx context.Context) (resp *schema.SiteUsersResp, err error) { resp = &schema.SiteUsersResp{} if err = s.GetSiteInfoByType(ctx, constant.SiteTypeUsers, resp); err != nil { return nil, err @@ -78,13 +82,13 @@ func (s *SiteInfoCommonService) GetSiteUsers(ctx context.Context) (resp *schema. } // FormatAvatar format avatar -func (s *SiteInfoCommonService) FormatAvatar(ctx context.Context, originalAvatarData, email string) *schema.AvatarInfo { +func (s *siteInfoCommonService) FormatAvatar(ctx context.Context, originalAvatarData, email string) *schema.AvatarInfo { gravatarBaseURL, defaultAvatar := s.getAvatarDefaultConfig(ctx) return s.selectedAvatar(originalAvatarData, defaultAvatar, gravatarBaseURL, email) } // FormatListAvatar format avatar -func (s *SiteInfoCommonService) FormatListAvatar(ctx context.Context, userList []*entity.User) ( +func (s *siteInfoCommonService) FormatListAvatar(ctx context.Context, userList []*entity.User) ( avatarMapping map[string]*schema.AvatarInfo) { gravatarBaseURL, defaultAvatar := s.getAvatarDefaultConfig(ctx) avatarMapping = make(map[string]*schema.AvatarInfo) @@ -94,7 +98,7 @@ func (s *SiteInfoCommonService) FormatListAvatar(ctx context.Context, userList [ return avatarMapping } -func (s *SiteInfoCommonService) getAvatarDefaultConfig(ctx context.Context) (string, string) { +func (s *siteInfoCommonService) getAvatarDefaultConfig(ctx context.Context) (string, string) { gravatarBaseURL, defaultAvatar := constant.DefaultGravatarBaseURL, constant.DefaultAvatar usersConfig, err := s.GetSiteUsers(ctx) if err != nil { @@ -106,7 +110,7 @@ func (s *SiteInfoCommonService) getAvatarDefaultConfig(ctx context.Context) (str return gravatarBaseURL, defaultAvatar } -func (s *SiteInfoCommonService) selectedAvatar( +func (s *siteInfoCommonService) selectedAvatar( originalAvatarData string, defaultAvatar string, gravatarBaseURL string, email string) *schema.AvatarInfo { avatarInfo := &schema.AvatarInfo{} _ = json.Unmarshal([]byte(originalAvatarData), avatarInfo) @@ -121,7 +125,7 @@ func (s *SiteInfoCommonService) selectedAvatar( } // GetSiteWrite get site info write -func (s *SiteInfoCommonService) GetSiteWrite(ctx context.Context) (resp *schema.SiteWriteResp, err error) { +func (s *siteInfoCommonService) GetSiteWrite(ctx context.Context) (resp *schema.SiteWriteResp, err error) { resp = &schema.SiteWriteResp{} if err = s.GetSiteInfoByType(ctx, constant.SiteTypeWrite, resp); err != nil { return nil, err @@ -130,7 +134,7 @@ func (s *SiteInfoCommonService) GetSiteWrite(ctx context.Context) (resp *schema. } // GetSiteLegal get site info write -func (s *SiteInfoCommonService) GetSiteLegal(ctx context.Context) (resp *schema.SiteLegalResp, err error) { +func (s *siteInfoCommonService) GetSiteLegal(ctx context.Context) (resp *schema.SiteLegalResp, err error) { resp = &schema.SiteLegalResp{} if err = s.GetSiteInfoByType(ctx, constant.SiteTypeLegal, resp); err != nil { return nil, err @@ -139,7 +143,7 @@ func (s *SiteInfoCommonService) GetSiteLegal(ctx context.Context) (resp *schema. } // GetSiteLogin get site login config -func (s *SiteInfoCommonService) GetSiteLogin(ctx context.Context) (resp *schema.SiteLoginResp, err error) { +func (s *siteInfoCommonService) GetSiteLogin(ctx context.Context) (resp *schema.SiteLoginResp, err error) { resp = &schema.SiteLoginResp{} if err = s.GetSiteInfoByType(ctx, constant.SiteTypeLogin, resp); err != nil { return nil, err @@ -148,7 +152,7 @@ func (s *SiteInfoCommonService) GetSiteLogin(ctx context.Context) (resp *schema. } // GetSiteCustomCssHTML get site custom css html config -func (s *SiteInfoCommonService) GetSiteCustomCssHTML(ctx context.Context) (resp *schema.SiteCustomCssHTMLResp, err error) { +func (s *siteInfoCommonService) GetSiteCustomCssHTML(ctx context.Context) (resp *schema.SiteCustomCssHTMLResp, err error) { resp = &schema.SiteCustomCssHTMLResp{} if err = s.GetSiteInfoByType(ctx, constant.SiteTypeCustomCssHTML, resp); err != nil { return nil, err @@ -157,7 +161,7 @@ func (s *SiteInfoCommonService) GetSiteCustomCssHTML(ctx context.Context) (resp } // GetSiteTheme get site theme -func (s *SiteInfoCommonService) GetSiteTheme(ctx context.Context) (resp *schema.SiteThemeResp, err error) { +func (s *siteInfoCommonService) GetSiteTheme(ctx context.Context) (resp *schema.SiteThemeResp, err error) { resp = &schema.SiteThemeResp{ ThemeOptions: schema.GetThemeOptions, } @@ -169,15 +173,24 @@ func (s *SiteInfoCommonService) GetSiteTheme(ctx context.Context) (resp *schema. } // GetSiteSeo get site seo -func (s *SiteInfoCommonService) GetSiteSeo(ctx context.Context) (resp *schema.SiteSeoReq, err error) { - resp = &schema.SiteSeoReq{} +func (s *siteInfoCommonService) GetSiteSeo(ctx context.Context) (resp *schema.SiteSeoResp, err error) { + resp = &schema.SiteSeoResp{} if err = s.GetSiteInfoByType(ctx, constant.SiteTypeSeo, resp); err != nil { return nil, err } return resp, nil } -func (s *SiteInfoCommonService) GetSiteInfoByType(ctx context.Context, siteType string, resp interface{}) (err error) { +func (s *siteInfoCommonService) EnableShortID(ctx context.Context) (enabled bool) { + siteSeo, err := s.GetSiteSeo(ctx) + if err != nil { + log.Error(err) + return false + } + return siteSeo.IsShortLink() +} + +func (s *siteInfoCommonService) GetSiteInfoByType(ctx context.Context, siteType string, resp interface{}) (err error) { siteInfo, exist, err := s.siteInfoRepo.GetByType(ctx, siteType) if err != nil { return err diff --git a/internal/service/tag/tag_service.go b/internal/service/tag/tag_service.go index 23dc25de..d30de46d 100644 --- a/internal/service/tag/tag_service.go +++ b/internal/service/tag/tag_service.go @@ -10,6 +10,7 @@ import ( "github.com/answerdev/answer/internal/service/siteinfo_common" tagcommonser "github.com/answerdev/answer/internal/service/tag_common" "github.com/answerdev/answer/pkg/htmltext" + "github.com/jinzhu/copier" "github.com/answerdev/answer/internal/base/pager" "github.com/answerdev/answer/internal/base/reason" @@ -18,7 +19,6 @@ import ( "github.com/answerdev/answer/internal/service/activity_common" "github.com/answerdev/answer/internal/service/permission" "github.com/answerdev/answer/pkg/converter" - "github.com/jinzhu/copier" "github.com/segmentfault/pacman/errors" "github.com/segmentfault/pacman/log" ) @@ -29,7 +29,7 @@ type TagService struct { tagCommonService *tagcommonser.TagCommonService revisionService *revision_common.RevisionService followCommon activity_common.FollowRepo - siteInfoService *siteinfo_common.SiteInfoCommonService + siteInfoService siteinfo_common.SiteInfoCommonService } // NewTagService new tag service @@ -38,7 +38,7 @@ func NewTagService( tagCommonService *tagcommonser.TagCommonService, revisionService *revision_common.RevisionService, followCommon activity_common.FollowRepo, - siteInfoService *siteinfo_common.SiteInfoCommonService) *TagService { + siteInfoService siteinfo_common.SiteInfoCommonService) *TagService { return &TagService{ tagRepo: tagRepo, tagCommonService: tagCommonService, diff --git a/internal/service/tag_common/tag_common.go b/internal/service/tag_common/tag_common.go index 7332ab80..c7d23a43 100644 --- a/internal/service/tag_common/tag_common.go +++ b/internal/service/tag_common/tag_common.go @@ -61,7 +61,7 @@ type TagCommonService struct { tagCommonRepo TagCommonRepo tagRelRepo TagRelRepo tagRepo TagRepo - siteInfoService *siteinfo_common.SiteInfoCommonService + siteInfoService siteinfo_common.SiteInfoCommonService } // NewTagCommonService new tag service @@ -70,7 +70,7 @@ func NewTagCommonService( tagRelRepo TagRelRepo, tagRepo TagRepo, revisionService *revision_common.RevisionService, - siteInfoService *siteinfo_common.SiteInfoCommonService, + siteInfoService siteinfo_common.SiteInfoCommonService, ) *TagCommonService { return &TagCommonService{ tagCommonRepo: tagCommonRepo, diff --git a/internal/service/uploader/upload.go b/internal/service/uploader/upload.go index 3b978521..e354d925 100644 --- a/internal/service/uploader/upload.go +++ b/internal/service/uploader/upload.go @@ -61,12 +61,12 @@ type UploaderService interface { // uploaderService uploader service type uploaderService struct { serviceConfig *service_config.ServiceConfig - siteInfoService *siteinfo_common.SiteInfoCommonService + siteInfoService siteinfo_common.SiteInfoCommonService } // NewUploaderService new upload service func NewUploaderService(serviceConfig *service_config.ServiceConfig, - siteInfoService *siteinfo_common.SiteInfoCommonService) UploaderService { + siteInfoService siteinfo_common.SiteInfoCommonService) UploaderService { for _, subPath := range subPathList { err := dir.CreateDirIfNotExist(filepath.Join(serviceConfig.UploadPath, subPath)) if err != nil { diff --git a/internal/service/user_admin/user_backyard.go b/internal/service/user_admin/user_backyard.go index 86270e08..ad6ea194 100644 --- a/internal/service/user_admin/user_backyard.go +++ b/internal/service/user_admin/user_backyard.go @@ -41,7 +41,7 @@ type UserAdminService struct { authService *auth.AuthService userCommonService *usercommon.UserCommon userActivity activity.UserActiveActivityRepo - siteInfoCommonService *siteinfo_common.SiteInfoCommonService + siteInfoCommonService siteinfo_common.SiteInfoCommonService } // NewUserAdminService new user admin service @@ -51,7 +51,7 @@ func NewUserAdminService( authService *auth.AuthService, userCommonService *usercommon.UserCommon, userActivity activity.UserActiveActivityRepo, - siteInfoCommonService *siteinfo_common.SiteInfoCommonService, + siteInfoCommonService siteinfo_common.SiteInfoCommonService, ) *UserAdminService { return &UserAdminService{ userRepo: userRepo, diff --git a/internal/service/user_common/user.go b/internal/service/user_common/user.go index 9a451265..84a13f3e 100644 --- a/internal/service/user_common/user.go +++ b/internal/service/user_common/user.go @@ -44,14 +44,14 @@ type UserCommon struct { userRepo UserRepo userRoleService *role.UserRoleRelService authService *auth.AuthService - siteInfoCommonService *siteinfo_common.SiteInfoCommonService + siteInfoCommonService siteinfo_common.SiteInfoCommonService } func NewUserCommon( userRepo UserRepo, userRoleService *role.UserRoleRelService, authService *auth.AuthService, - siteInfoCommonService *siteinfo_common.SiteInfoCommonService, + siteInfoCommonService siteinfo_common.SiteInfoCommonService, ) *UserCommon { return &UserCommon{ userRepo: userRepo, diff --git a/internal/service/user_external_login/user_center_login_service.go b/internal/service/user_external_login/user_center_login_service.go index 9e870381..5f388c7f 100644 --- a/internal/service/user_external_login/user_center_login_service.go +++ b/internal/service/user_external_login/user_center_login_service.go @@ -27,7 +27,7 @@ type UserCenterLoginService struct { userExternalLoginRepo UserExternalLoginRepo userCommonService *usercommon.UserCommon userActivity activity.UserActiveActivityRepo - siteInfoCommonService *siteinfo_common.SiteInfoCommonService + siteInfoCommonService siteinfo_common.SiteInfoCommonService } // NewUserCenterLoginService new user external login service @@ -36,7 +36,7 @@ func NewUserCenterLoginService( userCommonService *usercommon.UserCommon, userExternalLoginRepo UserExternalLoginRepo, userActivity activity.UserActiveActivityRepo, - siteInfoCommonService *siteinfo_common.SiteInfoCommonService, + siteInfoCommonService siteinfo_common.SiteInfoCommonService, ) *UserCenterLoginService { return &UserCenterLoginService{ userRepo: userRepo, diff --git a/internal/service/user_external_login/user_external_login_service.go b/internal/service/user_external_login/user_external_login_service.go index 4b10aef4..7e439ba3 100644 --- a/internal/service/user_external_login/user_external_login_service.go +++ b/internal/service/user_external_login/user_external_login_service.go @@ -41,7 +41,7 @@ type UserExternalLoginService struct { userExternalLoginRepo UserExternalLoginRepo userCommonService *usercommon.UserCommon emailService *export.EmailService - siteInfoCommonService *siteinfo_common.SiteInfoCommonService + siteInfoCommonService siteinfo_common.SiteInfoCommonService userActivity activity.UserActiveActivityRepo } @@ -51,7 +51,7 @@ func NewUserExternalLoginService( userCommonService *usercommon.UserCommon, userExternalLoginRepo UserExternalLoginRepo, emailService *export.EmailService, - siteInfoCommonService *siteinfo_common.SiteInfoCommonService, + siteInfoCommonService siteinfo_common.SiteInfoCommonService, userActivity activity.UserActiveActivityRepo, ) *UserExternalLoginService { return &UserExternalLoginService{ diff --git a/internal/service/user_service.go b/internal/service/user_service.go index 2fa336ef..fbd91219 100644 --- a/internal/service/user_service.go +++ b/internal/service/user_service.go @@ -38,7 +38,7 @@ type UserService struct { activityRepo activity_common.ActivityRepo emailService *export.EmailService authService *auth.AuthService - siteInfoService *siteinfo_common.SiteInfoCommonService + siteInfoService siteinfo_common.SiteInfoCommonService userRoleService *role.UserRoleRelService userExternalLoginService *user_external_login.UserExternalLoginService } @@ -48,7 +48,7 @@ func NewUserService(userRepo usercommon.UserRepo, activityRepo activity_common.ActivityRepo, emailService *export.EmailService, authService *auth.AuthService, - siteInfoService *siteinfo_common.SiteInfoCommonService, + siteInfoService siteinfo_common.SiteInfoCommonService, userRoleService *role.UserRoleRelService, userCommonService *usercommon.UserCommon, userExternalLoginService *user_external_login.UserExternalLoginService, diff --git a/pkg/uid/sid.go b/pkg/uid/sid.go index 2e9f5117..27d162e5 100644 --- a/pkg/uid/sid.go +++ b/pkg/uid/sid.go @@ -8,8 +8,6 @@ import ( const salt = int64(100) -var ShortIDSwitch = false - // NumToString num to string func NumToShortID(id int64) string { sid := strconv.FormatInt(id, 10) @@ -45,14 +43,11 @@ func ShortIDToNum(code string) int64 { } func EnShortID(id string) string { - if ShortIDSwitch { - num, err := strconv.ParseInt(id, 10, 64) - if err != nil { - return id - } - return NumToShortID(num) + num, err := strconv.ParseInt(id, 10, 64) + if err != nil { + return id } - return id + return NumToShortID(num) } func DeShortID(sid string) string { diff --git a/pkg/uid/sid_test.go b/pkg/uid/sid_test.go index 96501a98..3c8ab899 100644 --- a/pkg/uid/sid_test.go +++ b/pkg/uid/sid_test.go @@ -31,7 +31,6 @@ func Test_ShortID(t *testing.T) { func Test_EnDeShortID(t *testing.T) { nums := []string{"0", "1", "10", "100", "1000", "10000", "100000", "1234567", "10000000000000000", "10010000000001316", "19930000000001316"} - ShortIDSwitch = true for _, num := range nums { code := EnShortID(num) denum := DeShortID(code)