From 0138a6c467680d0d2c42333a718122aab12c4804 Mon Sep 17 00:00:00 2001 From: wdvxdr Date: Tue, 27 Apr 2021 20:38:59 +0800 Subject: [PATCH] feat(global): lazy compile split url regex pattern --- coolq/cqcode.go | 4 ++-- global/param.go | 12 +++++++++++- server/http.go | 2 +- server/websocket.go | 2 +- 4 files changed, 15 insertions(+), 5 deletions(-) diff --git a/coolq/cqcode.go b/coolq/cqcode.go index f41a08a..9cbbb0d 100644 --- a/coolq/cqcode.go +++ b/coolq/cqcode.go @@ -1084,7 +1084,7 @@ func CQCodeUnescapeValue(content string) string { // makeImageOrVideoElem 图片 elem 生成器,单独拎出来,用于公用 func (bot *CQBot) makeImageOrVideoElem(d map[string]string, video, group bool) (message.IMessageElement, error) { f := d["file"] - if strings.HasPrefix(f, "http") || strings.HasPrefix(f, "https") { + if strings.HasPrefix(f, "http") { cache := d["cache"] c := d["c"] if cache == "" { @@ -1120,7 +1120,7 @@ func (bot *CQBot) makeImageOrVideoElem(d map[string]string, video, group bool) ( if err != nil { return nil, err } - if strings.HasPrefix(fu.Path, "/") && runtime.GOOS == `windows` { + if runtime.GOOS == `windows` && strings.HasPrefix(fu.Path, "/") { fu.Path = fu.Path[1:] } info, err := os.Stat(fu.Path) diff --git a/global/param.go b/global/param.go index eaaae6a..893d5cd 100644 --- a/global/param.go +++ b/global/param.go @@ -5,6 +5,7 @@ import ( "regexp" "strconv" "strings" + "sync" "github.com/tidwall/gjson" ) @@ -85,9 +86,18 @@ func VersionNameCompare(current, remote string) bool { return len(cur) < len(re) } +var ( + // once lazy compile the reg + once sync.Once + // reg is splitURL regex pattern. + reg *regexp.Regexp +) + // SplitURL 将给定URL字符串分割为两部分,用于URL预处理防止风控 func SplitURL(s string) []string { - reg := regexp.MustCompile(`(?i)[a-z\d][-a-z\d]{0,62}(\.[a-z\d][-a-z\d]{0,62})+\.?`) + once.Do(func() { // lazy init. + reg = regexp.MustCompile(`(?i)[a-z\d][-a-z\d]{0,62}(\.[a-z\d][-a-z\d]{0,62})+\.?`) + }) idx := reg.FindAllStringIndex(s, -1) if len(idx) == 0 { return []string{s} diff --git a/server/http.go b/server/http.go index 9604208..c77ae13 100644 --- a/server/http.go +++ b/server/http.go @@ -203,7 +203,7 @@ func (c *HTTPClient) onBotPushEvent(m *bytes.Buffer) { } func (s *httpServer) HandleActions(c *gin.Context) { - action := strings.ReplaceAll(c.Param("action"), "_async", "") + action := strings.TrimSuffix(c.Param("action"), "_async") log.Debugf("HTTPServer接收到API调用: %v", action) c.JSON(200, s.api.callAPI(action, httpContext{ctx: c})) } diff --git a/server/websocket.go b/server/websocket.go index a537a7b..7c9b910 100644 --- a/server/websocket.go +++ b/server/websocket.go @@ -388,7 +388,7 @@ func (c *webSocketConn) handleRequest(_ *coolq.CQBot, payload []byte) { } }() j := gjson.Parse(utils.B2S(payload)) - t := strings.ReplaceAll(j.Get("action").Str, "_async", "") + t := strings.TrimSuffix(j.Get("action").Str, "_async") log.Debugf("WS接收到API调用: %v 参数: %v", t, j.Get("params").Raw) ret := c.apiCaller.callAPI(t, j.Get("params")) if j.Get("echo").Exists() {