Skip to content

A Q&A platform software for teams at any scales. Whether it's a community forum, help center, or knowledge management platform, you can always count on Apache Answer.

refactor(path): remove init for path ignore var

LinkinStars7e9becd8f5ec
diff --git a/cmd/main.go b/cmd/main.go
index 192832ad..2a5ddaa1 100644
--- a/cmd/main.go
+++ b/cmd/main.go
@@ -48,7 +48,6 @@ func runApp() {
if err != nil {
panic(err)
}
- conf.GetPathIgnoreList()
app, cleanup, err := initApplication(
c.Debug, c.Server, c.Data.Database, c.Data.Cache, c.I18n, c.Swaggerui, c.ServiceConfig, log.GetLogger())
if err != nil {
diff --git a/configs/reserved-usernames.json b/configs/reserved-usernames.json
index 48ce6186..deb6c822 100644
--- a/configs/reserved-usernames.json
+++ b/configs/reserved-usernames.json
@@ -1 +1 @@
-["0","100","101","102","1xx","200","201","202","203","204","205","206","207","226","2xx","300","301","302","303","304","305","307","308","3xx","400","401","402","403","404","405","406","407","408","409","410","411","412","413","414","415","416","417","418","422","423","424","426","428","429","431","451","4xx","500","501","502","503","504","505","506","507","511","5xx","7xx","about","abuse","access","account","accounts","activate","activities","activity","ad","add","address","adm","admin","administration","administrator","ads","adult","advertising","affiliate","affiliates","ajax","all","alpha","analysis","analytics","android","anon","anonymous","api","app","apps","archive","archives","article","asct","asset","atom","auth","authentication","autoconfig","avatar","backup","balancer-manager","bank","banner","banners","beta","billing","bin","blog","blogs","board","book","bookmark","bot","bots","broadcasthost","bug","bugs","business","cache","cadastro","calendar","call","campaign","cancel","captcha","career","careers","cart","categories","category","cgi","cgi-bin","changelog","chat","check","checking","checkout","client","cliente","clients","code","codereview","comercial","comment","comments","communities","community","company","compare","compras","config","configuration","connect","contact","contact-us","contact_us","contactus","contest","contribute","corp","create","crypt","css","dashboard","data","db","default","delete","demo","design","designer","destroy","dev","devel","developer","developers","diagram","diary","dict","dictionary","die","dir","direct_messages","directory","dist","dns","doc","docker","docs","documentation","domain","download","downloads","ecommerce","edit","editor","edu","education","email","employment","empty","end","enterprise","entries","entry","error","errors","eval","event","everyone","exit","explore","export","facebook","faq","favorite","favorites","fbi","feature","features","feed","feedback","feeds","file","files","firewall","first","flash","fleet","fleets","flog","follow","followers","following","forgot","forgot-password","forgot_password","forgotpassword","form","forum","forums","founder","free","friend","friends","ftp","gadget","gadgets","game","games","get","ghost","gift","gifts","gist","git","github","graph","group","groups","guest","guests","help","home","homepage","hooks","host","hosting","hostmaster","hostname","howto","hpg","html","http","httpd","https","i","iamges","icon","icons","id","idea","ideas","image","images","imap","img","index","indice","info","information","inquiry","instagram","intranet","invitations","invite","ip","ipad","iphone","irc","is","isatap","issue","issues","it","item","items","java","javascript","job","jobs","join","js","json","jump","keys","keyserver","knowledgebase","language","languages","last","ldap-status","legal","license","link","links","linux","list","lists","local","localdomain","localhost","log","log-in","log-out","log_in","log_out","login","logout","logs","m","mac","mail","mail1","mail2","mail3","mail4","mail5","mailer","mailer-daemon","mailing","maintenance","manager","manual","map","maps","marketing","master","me","media","member","members","message","messages","messenger","microblog","microblogs","mine","mis","mob","mobile","movie","movies","mp3","msg","msn","music","musicas","mx","my","mysql","name","named","names","namespace","namespaces","nan","navi","navigation","net","network","new","news","newsletter","nick","nickname","no-reply","nobody","noc","noreply","notes","noticias","notification","notifications","notify","ns","ns1","ns10","ns2","ns3","ns4","ns5","ns6","ns7","ns8","ns9","null","oauth","oauth_clients","offer","offers","official","old","online","openid","operator","ops","order","orders","organization","organizations","orgs","overview","owner","owners","package","page","pager","pages","panel","passwd","password","patch","payment","perl","phone","photo","photoalbum","photos","php","phpmyadmin","phppgadmin","phpredisadmin","pic","pics","ping","plan","plans","plugin","plugins","policy","pop","pop3","popular","portal","post","postfix","postmaster","posts","pr","premium","press","price","pricing","privacy","privacy-policy","privacy_policy","privacypolicy","private","product","products","profile","project","projects","promo","pub","public","purpose","put","pw","python","query","random","ranking","read","readme","recent","recruit","recruitment","register","registration","release","releases","remote","remove","replies","reply","report","reports","repositories","repository","req","request","requests","res","reset","reset-password","reset_password","resetpassword","resource","resources","roc","root","rss","ruby","rule","rules","sag","sale","sales","sample","samples","save","school","script","scripts","search","secure","security","self","send","server","server-info","server-status","service","services","session","sessions","setting","settings","setup","share","shop","show","sign-in","sign-up","sign_in","sign_up","signin","signout","signup","site","sitemap","sites","smartphone","smtp","soporte","source","spec","special","sql","src","ssh","ssl","ssladmin","ssladministrator","sslwebmaster","staff","stage","staging","start","stat","state","static","stats","status","store","stores","stories","style","styleguide","styles","stylesheet","stylesheets","subdomain","subscribe","subscriptions","suporte","support","svn","swf","sys","sysadmin","sysadministrator","system","tablet","tablets","tag","tags","talk","task","tasks","team","teams","tech","telnet","term","terms","terms-of-service","terms_of_service","termsofservice","test","test1","test2","test3","teste","testing","tests","theme","themes","thread","threads","tls","tmp","todo","token","tokenserver","tool","tools","top","topic","topics","tos","tour","translations","trends","tutorial","tux","tv","twitter","undef","unfollow","unsubscribe","update","upload","uploads","uptime","url","usage","usenet","user","username","users","usr","usuario","util","uucp","vendas","ver","version","video","videos","visitor","vpn","watch","weather","web","webhook","webhooks","webmail","webmaster","website","websites","welcome","widget","widgets","wiki","win","windows","word","work","works","workshop","wpad","ww","wws","www","www1","www2","www3","www4","www5","www6","www7","wwws","wwww","xfn","xml","xmpp","xpg","xxx","yaml","year","yml","you","yourdomain","yourname","yoursite","yourusername"]
\ No newline at end of file
+["0","100","101","102","1xx","200","201","202","203","204","205","206","207","226","2xx","300","301","302","303","304","305","307","308","3xx","400","401","402","403","404","405","406","407","408","409","410","411","412","413","414","415","416","417","418","422","423","424","426","428","429","431","451","4xx","500","501","502","503","504","505","506","507","511","5xx","7xx","about","abuse","access","account","account-activation","account-recovery","account-suspended","accounts","activate","activities","activity","ad","add","address","adm","admin","administration","administrator","ads","adult","advertising","affiliate","affiliates","ajax","all","alpha","analysis","analytics","android","anon","anonymous","api","app","apps","archive","archives","article","asct","asset","atom","auth","auth-landing","authentication","autoconfig","avatar","backup","balancer-manager","bank","banner","banners","beta","billing","bin","blog","blogs","board","book","bookmark","bot","bots","broadcasthost","bug","bugs","business","cache","cadastro","calendar","call","campaign","cancel","captcha","career","careers","cart","categories","category","cgi","cgi-bin","changelog","change-email","chat","check","checking","checkout","client","cliente","clients","code","codereview","comercial","comment","comments","communities","community","company","compare","compras","config","configuration","confirm-new-email","confirm-email","connect","contact","contact-us","contact_us","contactus","contest","contribute","corp","create","crypt","css","dashboard","data","db","default","delete","demo","design","designer","destroy","dev","devel","developer","developers","diagram","diary","dict","dictionary","die","dir","direct_messages","directory","dist","dns","doc","docker","docs","documentation","domain","download","downloads","ecommerce","edit","editor","edu","education","email","employment","empty","end","enterprise","entries","entry","error","errors","eval","event","everyone","exit","explore","export","facebook","faq","favorite","favorites","fbi","feature","features","feed","feedback","feeds","file","files","firewall","first","flash","fleet","fleets","flog","follow","followers","following","forgot","forgot-password","forgot_password","forgotpassword","form","forum","forums","founder","free","friend","friends","ftp","gadget","gadgets","game","games","get","ghost","gift","gifts","gist","git","github","graph","group","groups","guest","guests","help","home","homepage","hooks","host","hosting","hostmaster","hostname","howto","hpg","html","http","httpd","https","i","iamges","icon","icons","id","idea","ideas","image","images","imap","img","index","indice","info","information","inquiry","instagram","intranet","invitations","invite","ip","ipad","iphone","irc","is","isatap","issue","issues","it","item","items","java","javascript","job","jobs","join","js","json","jump","keys","keyserver","knowledgebase","language","languages","last","ldap-status","legal","license","link","links","linux","list","lists","local","localdomain","localhost","log","log-in","log-out","log_in","log_out","login","logout","logs","m","mac","mail","mail1","mail2","mail3","mail4","mail5","mailer","mailer-daemon","mailing","maintenance","manager","manual","map","maps","marketing","master","me","media","member","members","message","messages","messenger","microblog","microblogs","mine","mis","mob","mobile","movie","movies","mp3","msg","msn","music","musicas","mx","my","mysql","name","named","names","namespace","namespaces","nan","navi","navigation","net","network","new","news","newsletter","nick","nickname","no-reply","nobody","noc","noreply","notes","noticias","notification","notifications","notify","ns","ns1","ns10","ns2","ns3","ns4","ns5","ns6","ns7","ns8","ns9","null","oauth","oauth_clients","offer","offers","official","old","online","openid","operator","ops","order","orders","organization","organizations","orgs","overview","owner","owners","package","page","pager","pages","panel","passwd","password","password-reset","patch","payment","perl","phone","photo","photoalbum","photos","php","phpmyadmin","phppgadmin","phpredisadmin","pic","pics","ping","plan","plans","plugin","plugins","policy","pop","pop3","popular","portal","post","postfix","postmaster","posts","pr","premium","press","price","pricing","privacy","privacy-policy","privacy_policy","privacypolicy","private","product","products","profile","project","projects","promo","pub","public","purpose","put","pw","python","query","random","ranking","read","readme","recent","recruit","recruitment","register","registration","release","releases","remote","remove","replies","reply","report","reports","repositories","repository","req","request","requests","res","reset","reset-password","reset_password","resetpassword","resource","resources","roc","root","rss","ruby","rule","rules","sag","sale","sales","sample","samples","save","school","script","scripts","search","secure","security","self","send","server","server-info","server-status","service","services","session","sessions","setting","settings","setup","share","shop","show","sign-in","sign-up","sign_in","sign_up","signin","signout","signup","site","sitemap","sites","smartphone","smtp","soporte","source","spec","special","sql","src","ssh","ssl","ssladmin","ssladministrator","sslwebmaster","staff","stage","staging","start","stat","state","static","stats","status","store","stores","stories","style","styleguide","styles","stylesheet","stylesheets","subdomain","subscribe","subscriptions","suporte","support","svn","swf","sys","sysadmin","sysadministrator","system","tablet","tablets","tag","tags","talk","task","tasks","team","teams","tech","telnet","term","terms","terms-of-service","terms_of_service","termsofservice","test","test1","test2","test3","teste","testing","tests","theme","themes","thread","threads","tls","tmp","todo","token","tokenserver","tool","tools","top","topic","topics","tos","tour","translations","trends","tutorial","tux","tv","twitter","undef","unfollow","unsubscribe","update","upload","uploads","uptime","url","usage","usenet","user","username","users","usr","usuario","util","uucp","vendas","ver","version","video","videos","visitor","vpn","watch","weather","web","webhook","webhooks","webmail","webmaster","website","websites","welcome","widget","widgets","wiki","win","windows","word","work","works","workshop","wpad","ww","wws","www","www1","www2","www3","www4","www5","www6","www7","wwws","wwww","xfn","xml","xmpp","xpg","xxx","yaml","year","yml","you","yourdomain","yourname","yoursite","yourusername"]
\ No newline at end of file
diff --git a/internal/base/conf/conf.go b/internal/base/conf/conf.go
index 615405f1..b0401e1e 100644
--- a/internal/base/conf/conf.go
+++ b/internal/base/conf/conf.go
@@ -4,8 +4,6 @@ import (
"bytes"
"path/filepath"
- "github.com/answerdev/answer/configs"
- "github.com/answerdev/answer/internal/base/constant"
"github.com/answerdev/answer/internal/base/data"
"github.com/answerdev/answer/internal/base/server"
"github.com/answerdev/answer/internal/base/translator"
@@ -14,7 +12,6 @@ import (
"github.com/answerdev/answer/internal/service/service_config"
"github.com/answerdev/answer/pkg/writer"
"github.com/segmentfault/pacman/contrib/conf/viper"
- "github.com/segmentfault/pacman/log"
"gopkg.in/yaml.v3"
)
@@ -69,18 +66,3 @@ func RewriteConfig(configFilePath string, allConfig *AllConfig) error {
}
return writer.ReplaceFile(configFilePath, buf.String())
}
-
-func GetPathIgnoreList() map[string]bool {
- list := make(map[string]bool, 0)
- data := &PathIgnore{}
- err := yaml.Unmarshal(configs.PathIgnore, data)
- if err != nil {
- log.Error(err)
- return list
- }
- for _, item := range data.Users {
- list[item] = true
- }
- constant.PathIgnoreMap = list
- return list
-}
diff --git a/internal/base/constant/cache_key.go b/internal/base/constant/cache_key.go
new file mode 100644
index 00000000..9e9f9949
--- /dev/null
+++ b/internal/base/constant/cache_key.go
@@ -0,0 +1,19 @@
+package constant
+
+import "time"
+
+const (
+ UserStatusChangedCacheKey = "answer:user:status:"
+ UserStatusChangedCacheTime = 7 * 24 * time.Hour
+ UserTokenCacheKey = "answer:user:token:"
+ UserTokenCacheTime = 7 * 24 * time.Hour
+ AdminTokenCacheKey = "answer:admin:token:"
+ AdminTokenCacheTime = 7 * 24 * time.Hour
+ UserTokenMappingCacheKey = "answer:user-token:mapping:"
+ SiteInfoCacheKey = "answer:site-info:"
+ SiteInfoCacheTime = 1 * time.Hour
+ ConfigID2KEYCacheKeyPrefix = "answer:config:id:"
+ ConfigKEY2ContentCacheKeyPrefix = "answer:config:key:"
+ ConnectorUserExternalInfoCacheKey = "answer:connector:"
+ ConnectorUserExternalInfoCacheTime = 10 * time.Minute
+)
diff --git a/internal/base/constant/config_key.go b/internal/base/constant/config_key.go
deleted file mode 100644
index fb8be903..00000000
--- a/internal/base/constant/config_key.go
+++ /dev/null
@@ -1,7 +0,0 @@
-package constant
-
-const (
- PluginStatus = "plugin.status"
- ConfigID2KEYCacheKeyPrefix = "answer:config:id:"
- ConfigKEY2ContentCacheKeyPrefix = "answer:config:key:"
-)
diff --git a/internal/base/constant/connector.go b/internal/base/constant/connector.go
deleted file mode 100644
index fcf181f4..00000000
--- a/internal/base/constant/connector.go
+++ /dev/null
@@ -1,8 +0,0 @@
-package constant
-
-import "time"
-
-const (
- ConnectorUserExternalInfoCacheKey = "answer:connector:"
- ConnectorUserExternalInfoCacheTime = 10 * time.Minute
-)
diff --git a/internal/base/constant/constant.go b/internal/base/constant/constant.go
index b921c9f6..a6f271c9 100644
--- a/internal/base/constant/constant.go
+++ b/internal/base/constant/constant.go
@@ -1,76 +1,10 @@
package constant
-import "time"
-
-const (
- DefaultPageSize = 20 // Default number of pages
- UserStatusChangedCacheKey = "answer:user:status:"
- UserStatusChangedCacheTime = 7 * 24 * time.Hour
- UserTokenCacheKey = "answer:user:token:"
- UserTokenCacheTime = 7 * 24 * time.Hour
- AdminTokenCacheKey = "answer:admin:token:"
- AdminTokenCacheTime = 7 * 24 * time.Hour
- AcceptLanguageFlag = "Accept-Language"
- UserTokenMappingCacheKey = "answer:user-token:mapping:"
- SiteInfoCacheKey = "answer:site-info:"
- SiteInfoCacheTime = 1 * time.Hour
-)
-
const (
- QuestionObjectType = "question"
- AnswerObjectType = "answer"
- TagObjectType = "tag"
- UserObjectType = "user"
- CollectionObjectType = "collection"
- CommentObjectType = "comment"
- ReportObjectType = "report"
+ DefaultPageSize = 20 // Default number of pages
)
-// ObjectTypeStrMapping key => value
-// object TagID AnswerList
-// key equal database's table name
var (
Version string = ""
Revision string = ""
-
- PathIgnoreMap map[string]bool
-
- ObjectTypeStrMapping = map[string]int{
- QuestionObjectType: 1,
- AnswerObjectType: 2,
- TagObjectType: 3,
- UserObjectType: 4,
- CollectionObjectType: 6,
- CommentObjectType: 7,
- ReportObjectType: 8,
- }
-
- ObjectTypeNumberMapping = map[int]string{
- 1: QuestionObjectType,
- 2: AnswerObjectType,
- 3: TagObjectType,
- 4: UserObjectType,
- 6: CollectionObjectType,
- 7: CommentObjectType,
- 8: ReportObjectType,
- }
)
-
-const (
- SiteTypeGeneral = "general"
- SiteTypeInterface = "interface"
- SiteTypeBranding = "branding"
- SiteTypeWrite = "write"
- SiteTypeLegal = "legal"
- SiteTypeSeo = "seo"
- SiteTypeLogin = "login"
- SiteTypeCustomCssHTML = "css-html"
- SiteTypeTheme = "theme"
- SiteTypePrivileges = "privileges"
- SiteTypeUsers = "users"
-)
-
-func ExistInPathIgnore(name string) bool {
- _, ok := PathIgnoreMap[name]
- return ok
-}
diff --git a/internal/base/constant/http_header.go b/internal/base/constant/http_header.go
new file mode 100644
index 00000000..a68db8b1
--- /dev/null
+++ b/internal/base/constant/http_header.go
@@ -0,0 +1,5 @@
+package constant
+
+const (
+ AcceptLanguageFlag = "Accept-Language"
+)
diff --git a/internal/base/constant/object_type.go b/internal/base/constant/object_type.go
new file mode 100644
index 00000000..9c2c7124
--- /dev/null
+++ b/internal/base/constant/object_type.go
@@ -0,0 +1,33 @@
+package constant
+
+const (
+ QuestionObjectType = "question"
+ AnswerObjectType = "answer"
+ TagObjectType = "tag"
+ UserObjectType = "user"
+ CollectionObjectType = "collection"
+ CommentObjectType = "comment"
+ ReportObjectType = "report"
+)
+
+var (
+ ObjectTypeStrMapping = map[string]int{
+ QuestionObjectType: 1,
+ AnswerObjectType: 2,
+ TagObjectType: 3,
+ UserObjectType: 4,
+ CollectionObjectType: 6,
+ CommentObjectType: 7,
+ ReportObjectType: 8,
+ }
+
+ ObjectTypeNumberMapping = map[int]string{
+ 1: QuestionObjectType,
+ 2: AnswerObjectType,
+ 3: TagObjectType,
+ 4: UserObjectType,
+ 6: CollectionObjectType,
+ 7: CommentObjectType,
+ 8: ReportObjectType,
+ }
+)
diff --git a/internal/base/constant/plugin_config_key.go b/internal/base/constant/plugin_config_key.go
new file mode 100644
index 00000000..a184badf
--- /dev/null
+++ b/internal/base/constant/plugin_config_key.go
@@ -0,0 +1,5 @@
+package constant
+
+const (
+ PluginStatus = "plugin.status"
+)
diff --git a/internal/base/constant/rank.go b/internal/base/constant/privilege.go
similarity index 100%
rename from internal/base/constant/rank.go
rename to internal/base/constant/privilege.go
diff --git a/internal/base/constant/site_type.go b/internal/base/constant/site_type.go
new file mode 100644
index 00000000..72ad7b91
--- /dev/null
+++ b/internal/base/constant/site_type.go
@@ -0,0 +1,15 @@
+package constant
+
+const (
+ SiteTypeGeneral = "general"
+ SiteTypeInterface = "interface"
+ SiteTypeBranding = "branding"
+ SiteTypeWrite = "write"
+ SiteTypeLegal = "legal"
+ SiteTypeSeo = "seo"
+ SiteTypeLogin = "login"
+ SiteTypeCustomCssHTML = "css-html"
+ SiteTypeTheme = "theme"
+ SiteTypePrivileges = "privileges"
+ SiteTypeUsers = "users"
+)
diff --git a/internal/controller/template_controller.go b/internal/controller/template_controller.go
index 3a2bd095..589be128 100644
--- a/internal/controller/template_controller.go
+++ b/internal/controller/template_controller.go
@@ -14,6 +14,7 @@ import (
templaterender "github.com/answerdev/answer/internal/controller/template_render"
"github.com/answerdev/answer/internal/schema"
"github.com/answerdev/answer/internal/service/siteinfo_common"
+ "github.com/answerdev/answer/pkg/checker"
"github.com/answerdev/answer/pkg/converter"
"github.com/answerdev/answer/pkg/htmltext"
"github.com/answerdev/answer/pkg/obj"
@@ -421,7 +422,8 @@ func (tc *TemplateController) UserInfo(ctx *gin.Context) {
tc.Page404(ctx)
return
}
- exist := constant.ExistInPathIgnore(username)
+
+ exist := checker.IsUsersIgnorePath(username)
if exist {
file, err := ui.Build.ReadFile("build/index.html")
if err != nil {
diff --git a/pkg/checker/path_ignore.go b/pkg/checker/path_ignore.go
new file mode 100644
index 00000000..127ea7de
--- /dev/null
+++ b/pkg/checker/path_ignore.go
@@ -0,0 +1,47 @@
+package checker
+
+import (
+ "sync"
+
+ "github.com/answerdev/answer/configs"
+ "github.com/segmentfault/pacman/log"
+ "gopkg.in/yaml.v3"
+)
+
+type PathIgnore struct {
+ Users []string `yaml:"users"`
+ Questions []string `yaml:"questions"`
+}
+
+var (
+ ignorePathInit sync.Once
+ pathIgnore = &PathIgnore{}
+)
+
+func initPathIgnore() {
+ if err := yaml.Unmarshal(configs.PathIgnore, pathIgnore); err != nil {
+ log.Error(err)
+ }
+}
+
+// IsUsersIgnorePath checks whether the username is in ignore path
+func IsUsersIgnorePath(username string) bool {
+ ignorePathInit.Do(initPathIgnore)
+ for _, u := range pathIgnore.Users {
+ if u == username {
+ return true
+ }
+ }
+ return false
+}
+
+// IsQuestionsIgnorePath checks whether the questionID is in ignore path
+func IsQuestionsIgnorePath(questionID string) bool {
+ ignorePathInit.Do(initPathIgnore)
+ for _, u := range pathIgnore.Questions {
+ if u == questionID {
+ return true
+ }
+ }
+ return false
+}