Преглед на файлове

wip:赛思get请求参数替换走配置文件修改

wangkaiyue преди 2 години
родител
ревизия
6e26cd1ab2
променени са 3 файла, в които са добавени 138 реда и са изтрити 55 реда
  1. 103 29
      core/proxy/broker/outServer/SussBi.go
  2. 6 4
      core/proxy/proxyServer.go
  3. 29 22
      etc/config.yaml

+ 103 - 29
core/proxy/broker/outServer/SussBi.go

@@ -12,6 +12,7 @@ import (
 	"net/http"
 	"net/http/cookiejar"
 	"net/url"
+	"regexp"
 	"strings"
 )
 
@@ -21,12 +22,76 @@ type sussBi struct {
 	pwd  string
 	Url  *url.URL
 	jar  *cookiejar.Jar
+	prm  *ParamReplaceManager
 }
 
-func InitSussBi(address, user, password string) *sussBi {
-	sussCookie, _ := cookiejar.New(&cookiejar.Options{
+//参数替换
+type ParamReplace struct {
+	Replace []ParamReplaceSetting
+	Match   []ParamReplaceSetting
+}
+
+type ParamReplaceSetting struct {
+	Key, Value string
+}
+
+type ParamReplaceManager struct {
+	eqRouters   map[string]*ParamReplace
+	regexRouter map[*regexp.Regexp]*ParamReplace
+}
+
+func InitSussBi(config map[string]interface{}) (*sussBi, error) {
+	address := gconv.String(config["addr"])
+	user := gconv.String(config["user"])
+	password := gconv.String(config["password"])
+	paramReplace := gconv.Map(config["paramReplace"])
+	if address == "" {
+		return nil, fmt.Errorf("配置异常")
+	}
+	sussCookie, err := cookiejar.New(&cookiejar.Options{
 		PublicSuffixList: publicsuffix.List,
 	})
+	if err != nil {
+		return nil, fmt.Errorf("初始化cookie异常")
+	}
+	prManager := &ParamReplaceManager{
+		eqRouters:   map[string]*ParamReplace{},
+		regexRouter: map[*regexp.Regexp]*ParamReplace{},
+	}
+
+	for url, setting := range paramReplace {
+		pr := &ParamReplace{}
+		settingMap := gconv.Map(setting)
+		if settingMap == nil || len(settingMap) == 0 {
+			continue
+		}
+		if replaceMap := gconv.Map(settingMap["replace"]); replaceMap != nil && len(replaceMap) > 0 {
+			for k, v := range replaceMap {
+				pr.Replace = append(pr.Replace, ParamReplaceSetting{
+					Key:   k,
+					Value: gconv.String(v),
+				})
+			}
+		}
+		if replaceMap := gconv.Map(settingMap["match"]); replaceMap != nil && len(replaceMap) > 0 {
+			for k, v := range replaceMap {
+				pr.Match = append(pr.Replace, ParamReplaceSetting{
+					Key:   k,
+					Value: gconv.String(v),
+				})
+			}
+		}
+		if len(pr.Match) == 0 && len(pr.Replace) == 0 {
+			continue
+		}
+		if regexp.QuoteMeta(url) == url {
+			prManager.eqRouters[url] = pr
+		} else {
+			if reg, err := regexp.Compile(url); err == nil {
+				prManager.regexRouter[reg] = pr
+			}
+		}
+	}
 	u, _ := url.Parse(address)
 	return &sussBi{
 		addr: address,
@@ -34,7 +99,8 @@ func InitSussBi(address, user, password string) *sussBi {
 		Url:  u,
 		pwd:  password,
 		jar:  sussCookie,
-	}
+		prm:  prManager,
+	}, nil
 }
 
 // AutoLogin 自动登录
@@ -71,50 +137,58 @@ func (s *sussBi) CheckLoginOut(r *ghttp.Request) bool {
 func (s *sussBi) Filter(r *ghttp.Request) error {
 	ctx := router.GetGContext(r.GetCtx())
 	if ctx.Sess.NewUid != 0 {
+		replaceMap := map[string]interface{}{
+			"jyUserPositionId": ctx.Sess.UserPositionId,
+			"jyUserAccountId":  ctx.Sess.UserAccountId,
+			"jyEntPositionId":  ctx.Sess.EntPositionId,
+			"jyEntAccountId":   ctx.Sess.EntAccountId,
+			"jyUserName":       ctx.Sess.UserName,
+			"jyEntName":        ctx.Sess.EntName,
+			"jyEntId":          ctx.Sess.EntId,
+			"jyUserId":         ctx.Sess.NewUid,
+		}
 		if r.Request.Method == http.MethodPost {
 			bodyBytes, err := io.ReadAll(r.Request.Body)
 			if err != nil {
 				return err
 			}
 			if len(bodyBytes) > 0 {
-				replaceMap := map[string]interface{}{
-					"jyUserPositionId": ctx.Sess.UserPositionId,
-					"jyUserAccountId":  ctx.Sess.UserAccountId,
-					"jyEntPositionId":  ctx.Sess.EntPositionId,
-					"jyEntAccountId":   ctx.Sess.EntAccountId,
-					"jyUserName":       ctx.Sess.UserName,
-					"jyEntName":        ctx.Sess.EntName,
-					"jyEntId":          ctx.Sess.EntId,
-				}
-				finalBytes := bytes.ReplaceAll(bodyBytes, []byte(`"jyUserId"`), []byte(fmt.Sprintf(`"%d"`, ctx.Sess.NewUid)))
+				finalBytes := bodyBytes
 				for k, v := range replaceMap {
 					finalBytes = bytes.ReplaceAll(finalBytes, []byte(`"`+k+`"`), []byte(`"`+fmt.Sprint(v)+`"`))
 				}
 				r.ContentLength = gconv.Int64(len(finalBytes))
 				r.Request.Header.Set("Content-Length", fmt.Sprintf("%d", len(finalBytes)))
-				//fmt.Printf("before len:%d value:%s\nafter: len:%d value:%s\n", len(bodyBytes), string(bodyBytes), len(finalBytes), string(finalBytes))
-				//fmt.Printf("header %+v\n", r.Request.Header)
 				r.Request.Body = ioutil.NopCloser(bytes.NewReader(finalBytes))
 			}
 		} else if r.Request.Method == http.MethodGet {
-			// 年终报告pdf增加职位id
-			if strings.HasPrefix(r.RequestURI, "/api/meta/services/convertFileToPDF") {
-				if newValues, err := url.ParseQuery(r.URL.RawQuery); err == nil && len(newValues) > 0 {
-					if _, ok := newValues["QUERY_PARAM_M_POSITION_ID"]; ok {
-						newValues["QUERY_PARAM_M_POSITION_ID"] = []string{fmt.Sprintf("%d", ctx.Sess.UserPositionId)}
-					}
-					if _, ok := newValues["position_id"]; ok {
-						newValues["position_id"] = []string{fmt.Sprintf("%d", ctx.Sess.UserPositionId)}
+			var prArr *ParamReplace
+			if rule, ok := s.prm.eqRouters[r.URL.Path]; ok && rule != nil {
+				prArr = rule
+			} else {
+				for reg, rule := range s.prm.regexRouter {
+					if reg.MatchString(r.URL.Path) {
+						prArr = rule
+						break
 					}
-					r.URL.RawQuery = newValues.Encode()
 				}
 			}
-
-			if strings.HasPrefix(r.RequestURI, "/api/dw/services/downloadAttachment") || strings.HasPrefix(r.RequestURI, "/api/dw/services/getDwAttachments") {
+			if prArr != nil {
 				if newValues, err := url.ParseQuery(r.URL.RawQuery); err == nil && len(newValues) > 0 {
-					if value, ok := newValues["params"]; ok && len(value) > 0 {
-						newValue := strings.ReplaceAll(value[0], "jyUserPositionId", fmt.Sprintf("%d", ctx.Sess.UserPositionId))
-						newValues["params"] = []string{newValue}
+					for _, replace := range prArr.Replace {
+						if replace.Key != "" && replace.Value != "" && replaceMap[replace.Value] != nil {
+							newValues[replace.Key] = []string{fmt.Sprintf("%v", replaceMap[replace.Value])}
+						}
+					}
+					for _, match := range prArr.Match {
+						if match.Key != "" && match.Value != "" {
+							if arr := strings.Split(match.Key, "."); len(arr) == 2 && replaceMap[match.Value] != nil {
+								if value, ok := newValues[arr[0]]; ok && len(value) > 0 {
+									newValue := strings.ReplaceAll(value[0], arr[1], fmt.Sprintf("%v", replaceMap[match.Value]))
+									newValues[arr[0]] = []string{newValue}
+								}
+							}
+						}
 					}
 					r.URL.RawQuery = newValues.Encode()
 				}

+ 6 - 4
core/proxy/proxyServer.go

@@ -36,10 +36,12 @@ func InitGateWayServer() *ghttp.Server {
 		g.Log().Error(initCtx, err)
 	}
 	//初始化外部服务
-	sussBiServer := outServer.InitSussBi(gcfg.Instance().MustGet(initCtx, "outServer.sussbi.addr", nil).String(),
-		gcfg.Instance().MustGet(initCtx, "outServer.sussbi.user", nil).String(),
-		gcfg.Instance().MustGet(initCtx, "outServer.sussbi.password", nil).String())
-	vars.BManager.RegisterOutServer(sussBiServer.Url, sussBiServer)
+	sussBiServer, err := outServer.InitSussBi(gcfg.Instance().MustGet(initCtx, "outServer.sussbi", nil).Map())
+	if err != nil {
+		g.Log().Error(initCtx, err)
+	} else {
+		vars.BManager.RegisterOutServer(sussBiServer.Url, sussBiServer)
+	}
 
 	gateWayServer := g.Server()
 	//关闭系统自带请求日志

+ 29 - 22
etc/config.yaml

@@ -1,3 +1,4 @@
+# 代理网关服务配置
 server:
   # 基本配置
   address: :8077                          # 本地监听地址。默认":80"
@@ -32,10 +33,11 @@ etcd:
 #数据库配置
 databases:
   # redis配置
-  redis: session=192.168.3.206:1712,other=192.168.3.11:1712    # 用户获取剑鱼程序用户session
+  redis: session=192.168.3.11:1713,other=192.168.3.11:1712 # session用户获取剑鱼程序用户session  other用户获取剑鱼权益redis
   polyredis:
-    address: 192.168.3.206:1712
+    address: 192.168.3.11:1713
     poolsize: 30
+
   # mysql配置
   mysql:
     dbName: base_service
@@ -44,7 +46,6 @@ databases:
     passWord: =PDT49#80Z!RVv52_z
     maxOpenConns: 5
     maxIdleConns: 5
-
   # jianyu mysql配置
   mysqlJy:
     dbName: jianyu
@@ -72,7 +73,6 @@ databases:
 
 # 系统配置
 system:
-  routerTable: front_proxy
   # 监听服务注册etcd配置
   etcdListen:
     - 192.168.3.206:2379
@@ -94,18 +94,16 @@ proxy:
 
 #日志配置
 logger:
-  level: "ALL"                # ALL, DEV, PROD
+  level: "PROD"                # ALL, DEV, PROD
   default:
-    level: "ALL"
     file: "{Y-m-d}.log"
     rotateExpire: 10
     rotateBackupLimit: 10
     stdout: true
-    stStatus: 0
     path: "./logs/system"
   reqLog:
-    level: "ALL"
-    saveToDb: false
+    level: "PROD"
+    saveToDb: true
     path: "./logs/request"
     file: "{Y-m-d}.log"        # 日志文件格式
     stdout: true               # 是否输出至控制台
@@ -113,24 +111,33 @@ logger:
     rotateBackupExpire: 60s    # 切分文件的过期时间为7d,即七天后会自动删除该切分文件
     rotateBackupCompress: 0   # 滚动切分文件的压缩比(0-9)。默认为0,表示不压缩
 
-  # 系统告警
-  alarm:
-    isOpen: false                        # 异常通知开关。默认关闭
-    address: 192.168.3.207:4150         # nsq消息通知地址。默认关闭
-    toppic: jyalert                     # 消息管道
-    isJsonEncode: false                 # 是否加密
-    id: pre_alert                       # id
-    title: 你有新的告警消息处理            # 消息标题
-    text: 前置代理告警请查看               # 消息正文
+# 系统告警
+alarm:
+  isOpen: true                        # 异常通知开关。默认关闭
+  address: 192.168.3.207:4150         # nsq消息通知地址。默认关闭
+  toppic: jyalert                     # 消息管道
+  isJsonEncode: false                 # 是否加密
+  id: pre_alert                       # id
+  title: 你有新的告警消息处理            # 消息标题
+  text: 前置代理告警请查看               # 消息正文
 outServer:
   sussbi:
-    addr: http://192.168.3.217:8088
+    addr: http://192.168.3.11:8012
     user: jianyuweb
     password: 111111
-  local:
-    addr: http://127.0.0.1:8080
+    paramReplace:
+      "/api/meta/services/convertFileToPDF":
+        replace:
+          QUERY_PARAM_M_POSITION_ID: "jyUserPositionId"
+          position_id: "jyUserPositionId"
+      "/api/dw/services/downloadAttachment":
+        match:
+          params.jyUserPositionId: "jyUserPositionId"
+      "/api/dw/services/getDwAttachments":
+        match:
+          params.jyUserPositionId: "jyUserPositionId"
 
 # 仅限此程序代理的地址
 noPowerUrlSwitch:
-  '/nzj/app/nzj.app/nzj_detail_1.spg' : '/nzj/app/nzj.app/nzj_detail_0.spg'
+  '/nzj/app/nzj.app/nzj_detail_1.spg': '/nzj/app/nzj.app/nzj_detail_0.spg'
   '/nzj/app/nzj.app/nzj_search_1.spg': '/nzj/app/nzj.app/nzj_search_0.spg'