webforwarding.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. package service
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. v1 "github.com/go-nunu/nunu-layout-advanced/api/v1"
  7. "github.com/go-nunu/nunu-layout-advanced/internal/model"
  8. "github.com/go-nunu/nunu-layout-advanced/internal/repository"
  9. "github.com/go-nunu/nunu-layout-advanced/pkg/rabbitmq"
  10. amqp "github.com/rabbitmq/amqp091-go"
  11. "go.uber.org/zap"
  12. "golang.org/x/sync/errgroup"
  13. "sort"
  14. "strconv"
  15. "strings"
  16. )
  17. type WebForwardingService interface {
  18. GetWebForwarding(ctx context.Context, req v1.GetForwardingRequest) (v1.WebForwardingDataRequest, error)
  19. GetWebForwardingWafWebAllIps(ctx context.Context, req v1.GetForwardingRequest) ([]v1.WebForwardingDataRequest, error)
  20. AddWebForwarding(ctx context.Context, req *v1.WebForwardingRequest) error
  21. EditWebForwarding(ctx context.Context, req *v1.WebForwardingRequest) error
  22. DeleteWebForwarding(ctx context.Context, Ids []int) error
  23. }
  24. func NewWebForwardingService(
  25. service *Service,
  26. required RequiredService,
  27. webForwardingRepository repository.WebForwardingRepository,
  28. crawler CrawlerService,
  29. parser ParserService,
  30. wafformatter WafFormatterService,
  31. aoDun AoDunService,
  32. mq *rabbitmq.RabbitMQ,
  33. ) WebForwardingService {
  34. return &webForwardingService{
  35. Service: service,
  36. webForwardingRepository: webForwardingRepository,
  37. required: required,
  38. parser: parser,
  39. crawler: crawler,
  40. wafformatter: wafformatter,
  41. aoDun: aoDun,
  42. mq: mq,
  43. }
  44. }
  45. type webForwardingService struct {
  46. *Service
  47. webForwardingRepository repository.WebForwardingRepository
  48. required RequiredService
  49. parser ParserService
  50. crawler CrawlerService
  51. wafformatter WafFormatterService
  52. aoDun AoDunService
  53. mq *rabbitmq.RabbitMQ
  54. }
  55. func (s *webForwardingService) require(ctx context.Context,req v1.GlobalRequire) (v1.GlobalRequire, error) {
  56. var err error
  57. var res v1.GlobalRequire
  58. g, gCtx := errgroup.WithContext(ctx)
  59. g.Go(func() error {
  60. result, e := s.wafformatter.require(gCtx, req, "web")
  61. if e != nil {
  62. return e
  63. }
  64. res = result
  65. return nil
  66. })
  67. g.Go(func() error {
  68. e := s.wafformatter.validateWafDomainCount(gCtx, req)
  69. if e != nil {
  70. return e
  71. }
  72. return nil
  73. })
  74. if err = g.Wait(); err != nil {
  75. return v1.GlobalRequire{}, err
  76. }
  77. return res, nil
  78. }
  79. func (s *webForwardingService) GetWebForwarding(ctx context.Context, req v1.GetForwardingRequest) (v1.WebForwardingDataRequest, error) {
  80. var webForwarding model.WebForwarding
  81. var backend model.WebForwardingRule
  82. g, gCtx := errgroup.WithContext(ctx)
  83. g.Go(func() error {
  84. res, e := s.webForwardingRepository.GetWebForwarding(gCtx, int64(req.Id))
  85. if e != nil {
  86. // 直接返回错误,errgroup 会捕获它
  87. return fmt.Errorf("GetWebForwarding failed: %w", e)
  88. }
  89. if res != nil {
  90. webForwarding = *res
  91. }
  92. return nil
  93. })
  94. g.Go(func() error {
  95. res, e := s.webForwardingRepository.GetWebForwardingIpsByID(ctx, req.Id)
  96. if e != nil {
  97. return fmt.Errorf("GetWebForwardingByID failed: %w", e)
  98. }
  99. if res != nil {
  100. backend = *res
  101. }
  102. return nil
  103. })
  104. if err := g.Wait(); err != nil {
  105. return v1.WebForwardingDataRequest{}, err
  106. }
  107. return v1.WebForwardingDataRequest{
  108. Id: webForwarding.Id,
  109. WafWebId: webForwarding.WafWebId,
  110. Tag: webForwarding.Tag,
  111. Port: webForwarding.Port,
  112. Domain: webForwarding.Domain,
  113. CustomHost: webForwarding.CustomHost,
  114. WafWebLimitId: webForwarding.WebLimitRuleId,
  115. WafGatewayGroupId: webForwarding.WafGatewayGroupId,
  116. CcCount: webForwarding.CcCount,
  117. CcDuration: webForwarding.CcDuration,
  118. CcBlockCount: webForwarding.CcBlockCount,
  119. CcBlockDuration: webForwarding.CcBlockDuration,
  120. Cc4xxCount: webForwarding.Cc4xxCount,
  121. Cc4xxDuration: webForwarding.Cc4xxDuration,
  122. Cc4xxBlockCount: webForwarding.Cc4xxBlockCount,
  123. Cc4xxBlockDuration: webForwarding.Cc4xxBlockDuration,
  124. Cc5xxCount: webForwarding.Cc5xxCount,
  125. Cc5xxDuration: webForwarding.Cc5xxDuration,
  126. Cc5xxBlockCount: webForwarding.Cc5xxBlockCount,
  127. Cc5xxBlockDuration: webForwarding.Cc5xxBlockDuration,
  128. IsHttps: webForwarding.IsHttps,
  129. Comment: webForwarding.Comment,
  130. BackendList: backend.BackendList,
  131. AllowIpList: backend.AllowIpList,
  132. DenyIpList: backend.DenyIpList,
  133. AccessRule: backend.AccessRule,
  134. HttpsKey: webForwarding.HttpsKey,
  135. HttpsCert: webForwarding.HttpsCert,
  136. }, nil
  137. }
  138. // buildWafFormData 辅助函数,用于构建通用的 formData
  139. func (s *webForwardingService) buildWafFormData(req *v1.WebForwardingDataSend, require v1.GlobalRequire) map[string]interface{} {
  140. // 将BackendList序列化为JSON字符串
  141. backendJSON, err := json.MarshalIndent(req.BackendList, "", " ")
  142. var backendStr interface{}
  143. if err != nil {
  144. // 如果序列化失败,使用空数组
  145. backendStr = "[]"
  146. } else {
  147. // 成功序列化后,使用JSON字符串
  148. backendStr = string(backendJSON)
  149. }
  150. return map[string]interface{}{
  151. "waf_web_id": req.WafWebId,
  152. "tag": require.Tag,
  153. "port": req.Port,
  154. "domain": req.Domain,
  155. "custom_host": req.CustomHost,
  156. "waf_gateway_group_id": require.WafGatewayGroupId,
  157. "waf_web_limit_id": require.LimitRuleId,
  158. "cc_count": req.CcCount,
  159. "cc_duration": req.CcDuration,
  160. "cc_block_count": req.CcBlockCount,
  161. "cc_block_duration": req.CcBlockDuration,
  162. "cc_4xx_count": req.Cc4xxCount,
  163. "cc_4xx_duration": req.Cc4xxDuration,
  164. "cc_4xx_block_count": req.Cc4xxBlockCount,
  165. "cc_4xx_block_duration": req.Cc4xxBlockDuration,
  166. "cc_5xx_count": req.Cc5xxCount,
  167. "cc_5xx_duration": req.Cc5xxDuration,
  168. "cc_5xx_block_count": req.Cc5xxBlockCount,
  169. "cc_5xx_block_duration": req.Cc5xxBlockDuration,
  170. "backend": backendStr,
  171. "allow_ip_list": req.AllowIpList,
  172. "deny_ip_list": req.DenyIpList,
  173. "access_rule": req.AccessRule,
  174. "is_https": req.IsHttps,
  175. "comment": req.Comment,
  176. "https_cert": req.HttpsCert,
  177. "https_key": req.HttpsKey,
  178. }
  179. }
  180. // buildWebForwardingModel 辅助函数,用于构建通用的 WebForwarding 模型
  181. // ruleId 是从 WAF 系统获取的 ID
  182. func (s *webForwardingService) buildWebForwardingModel(req *v1.WebForwardingDataRequest,ruleId int, require v1.GlobalRequire) *model.WebForwarding {
  183. return &model.WebForwarding{
  184. HostId: require.HostId,
  185. WafWebId: ruleId,
  186. Tag: require.Tag,
  187. Port: req.Port,
  188. Domain: req.Domain,
  189. CustomHost: req.CustomHost,
  190. WafGatewayGroupId: require.WafGatewayGroupId,
  191. WebLimitRuleId: require.LimitRuleId,
  192. CcCount: req.CcCount,
  193. CcDuration: req.CcDuration,
  194. CcBlockCount: req.CcBlockCount,
  195. CcBlockDuration: req.CcBlockDuration,
  196. Cc4xxCount: req.Cc4xxCount,
  197. Cc4xxDuration: req.Cc4xxDuration,
  198. Cc4xxBlockCount: req.Cc4xxBlockCount,
  199. Cc4xxBlockDuration: req.Cc4xxBlockDuration,
  200. Cc5xxCount: req.Cc5xxCount,
  201. Cc5xxDuration: req.Cc5xxDuration,
  202. Cc5xxBlockCount: req.Cc5xxBlockCount,
  203. Cc5xxBlockDuration: req.Cc5xxBlockDuration,
  204. IsHttps: req.IsHttps,
  205. Comment: req.Comment,
  206. HttpsCert: req.HttpsCert,
  207. HttpsKey: req.HttpsKey,
  208. }
  209. }
  210. func (s *webForwardingService) buildWebRuleModel(reqData *v1.WebForwardingDataRequest, require v1.GlobalRequire, localDbId int) *model.WebForwardingRule {
  211. return &model.WebForwardingRule{
  212. Uid: require.Uid,
  213. HostId: require.HostId,
  214. WebId: localDbId, // 关联到本地数据库的主记录 ID
  215. BackendList: reqData.BackendList,
  216. AllowIpList: reqData.AllowIpList,
  217. DenyIpList: reqData.DenyIpList,
  218. AccessRule: reqData.AccessRule,
  219. }
  220. }
  221. func (s *webForwardingService) prepareWafData(ctx context.Context, req *v1.WebForwardingRequest) (v1.GlobalRequire, map[string]interface{}, error) {
  222. // 1. 获取必要的全局信息
  223. require, err := s.require(ctx, v1.GlobalRequire{
  224. HostId: req.HostId,
  225. Uid: req.Uid,
  226. Comment: req.WebForwardingData.Comment,
  227. Domain: req.WebForwardingData.Domain,
  228. })
  229. if err != nil {
  230. return v1.GlobalRequire{}, nil, err
  231. }
  232. if require.WafGatewayGroupId == 0 || require.LimitRuleId == 0 {
  233. return v1.GlobalRequire{}, nil, fmt.Errorf("请先配置实例")
  234. }
  235. // 2. 将字符串切片拼接成字符串,用于 WAF API
  236. allowIpListStr := strings.Join(req.WebForwardingData.AllowIpList, "\n")
  237. denyIpListStr := strings.Join(req.WebForwardingData.DenyIpList, "\n")
  238. PortInt, err := strconv.Atoi(req.WebForwardingData.Port)
  239. if err != nil {
  240. return v1.GlobalRequire{}, nil, err
  241. }
  242. // 3. 创建用于构建 WAF 表单的数据结构
  243. formDataBase := v1.WebForwardingDataSend{
  244. Tag: require.Tag,
  245. WafWebId: req.WebForwardingData.WafWebId,
  246. WafGatewayGroupId: require.WafGatewayGroupId,
  247. WafWebLimitId: require.LimitRuleId,
  248. Port: PortInt,
  249. Domain: req.WebForwardingData.Domain,
  250. CustomHost: req.WebForwardingData.CustomHost,
  251. CcCount: req.WebForwardingData.CcCount,
  252. CcDuration: req.WebForwardingData.CcDuration,
  253. CcBlockCount: req.WebForwardingData.CcBlockCount,
  254. CcBlockDuration: req.WebForwardingData.CcBlockDuration,
  255. Cc4xxCount: req.WebForwardingData.Cc4xxCount,
  256. Cc4xxDuration: req.WebForwardingData.Cc4xxDuration,
  257. Cc4xxBlockCount: req.WebForwardingData.Cc4xxBlockCount,
  258. Cc4xxBlockDuration: req.WebForwardingData.Cc4xxBlockDuration,
  259. Cc5xxCount: req.WebForwardingData.Cc5xxCount,
  260. Cc5xxDuration: req.WebForwardingData.Cc5xxDuration,
  261. Cc5xxBlockCount: req.WebForwardingData.Cc5xxBlockCount,
  262. Cc5xxBlockDuration: req.WebForwardingData.Cc5xxBlockDuration,
  263. IsHttps: req.WebForwardingData.IsHttps,
  264. BackendList: req.WebForwardingData.BackendList,
  265. AllowIpList: allowIpListStr,
  266. DenyIpList: denyIpListStr,
  267. AccessRule: req.WebForwardingData.AccessRule,
  268. Comment: req.WebForwardingData.Comment,
  269. HttpsCert: req.WebForwardingData.HttpsCert,
  270. HttpsKey: req.WebForwardingData.HttpsKey,
  271. }
  272. // 4. 构建 WAF 表单数据映射
  273. formData := s.buildWafFormData(&formDataBase, require)
  274. return require, formData, nil
  275. }
  276. func (s *webForwardingService) AddWebForwarding(ctx context.Context, req *v1.WebForwardingRequest) error {
  277. require, formData, err := s.prepareWafData(ctx, req)
  278. if err != nil {
  279. return err
  280. }
  281. err = s.wafformatter.validateWafPortCount(ctx, require.HostId)
  282. if err != nil {
  283. return err
  284. }
  285. wafWebId, err := s.wafformatter.sendFormData(ctx, "admin/info/waf_web/new", "admin/new/waf_web", formData)
  286. if err != nil {
  287. return err
  288. }
  289. // 异步任务:将域名添加到白名单
  290. go s.publishDomainWhitelistTask(req.WebForwardingData.Domain, "add")
  291. webModel := s.buildWebForwardingModel(&req.WebForwardingData, wafWebId, require)
  292. id, err := s.webForwardingRepository.AddWebForwarding(ctx, webModel)
  293. if err != nil {
  294. return err
  295. }
  296. webRuleModel := s.buildWebRuleModel(&req.WebForwardingData, require, id)
  297. //var ips []v1.IpInfo
  298. //for _, v := range req.WebForwardingData.AllowIpList {
  299. // ips = append(ips, v1.IpInfo{
  300. // FType: "allow",
  301. // FStartIp: v,
  302. // FEndIp: v,
  303. // FRemark: "宁波高防IP过白",
  304. // FServerIp: "",
  305. // })
  306. //}
  307. //err = s.aoDun.AddDomainWhiteList(ctx, req.WebForwardingData.Domain)
  308. if _, err = s.webForwardingRepository.AddWebForwardingIps(ctx, *webRuleModel); err != nil {
  309. return err
  310. }
  311. return nil
  312. }
  313. func (s *webForwardingService) EditWebForwarding(ctx context.Context, req *v1.WebForwardingRequest) error {
  314. WafWebId, err := s.webForwardingRepository.GetWebForwardingWafWebIdById(ctx, req.WebForwardingData.Id)
  315. if err != nil {
  316. return err
  317. }
  318. req.WebForwardingData.WafWebId = WafWebId
  319. require, formData, err := s.prepareWafData(ctx, req)
  320. if err != nil {
  321. return err
  322. }
  323. _, err = s.wafformatter.sendFormData(ctx, "admin/info/waf_web/edit?&__goadmin_edit_pk="+strconv.Itoa(req.WebForwardingData.WafWebId), "admin/edit/waf_web", formData)
  324. if err != nil {
  325. return err
  326. }
  327. webModel := s.buildWebForwardingModel(&req.WebForwardingData, req.WebForwardingData.WafWebId, require)
  328. webModel.Id = req.WebForwardingData.Id
  329. if err = s.webForwardingRepository.EditWebForwarding(ctx, webModel); err != nil {
  330. return err
  331. }
  332. webRuleModel := s.buildWebRuleModel(&req.WebForwardingData, require, req.WebForwardingData.Id)
  333. if err = s.webForwardingRepository.EditWebForwardingIps(ctx, *webRuleModel); err != nil {
  334. return err
  335. }
  336. return nil
  337. }
  338. func (s *webForwardingService) DeleteWebForwarding(ctx context.Context, Ids []int) error {
  339. for _, Id := range Ids {
  340. wafWebId, err := s.webForwardingRepository.GetWebForwardingWafWebIdById(ctx, Id)
  341. if err != nil {
  342. return err
  343. }
  344. _, err = s.crawler.DeleteRule(ctx, wafWebId, "admin/delete/waf_web?page=1&__pageSize=10&__sort=waf_web_id&__sort_type=desc")
  345. if err != nil {
  346. return err
  347. }
  348. if err = s.webForwardingRepository.DeleteWebForwarding(ctx, int64(Id)); err != nil {
  349. return err
  350. }
  351. if err = s.webForwardingRepository.DeleteWebForwardingIpsById(ctx, Id); err != nil {
  352. return err
  353. }
  354. }
  355. return nil
  356. }
  357. func (s *webForwardingService) GetWebForwardingWafWebAllIps(ctx context.Context, req v1.GetForwardingRequest) ([]v1.WebForwardingDataRequest, error) {
  358. type CombinedResult struct {
  359. Id int
  360. Forwarding *model.WebForwarding
  361. BackendRule *model.WebForwardingRule
  362. Err error // 如果此ID的处理出错,则携带错误
  363. }
  364. g, gCtx := errgroup.WithContext(ctx)
  365. ids, err := s.webForwardingRepository.GetWebForwardingWafWebAllIds(gCtx, req.HostId)
  366. if err != nil {
  367. return nil, fmt.Errorf("GetWebForwardingWafWebAllIds failed: %w", err)
  368. }
  369. if len(ids) == 0 {
  370. return nil, nil // 没有ID,直接返回空切片
  371. }
  372. // 创建一个通道来接收每个ID的处理结果
  373. // 通道缓冲区大小设为ID数量,这样发送者不会因为接收者慢而阻塞(在所有goroutine都启动后)
  374. resultsChan := make(chan CombinedResult, len(ids))
  375. for _, idVal := range ids {
  376. currentID := idVal // 捕获循环变量
  377. g.Go(func() error {
  378. var wf *model.WebForwarding
  379. var bk *model.WebForwardingRule
  380. var localErr error
  381. // 1. 获取 WebForwarding 信息
  382. wf, localErr = s.webForwardingRepository.GetWebForwarding(gCtx, int64(currentID))
  383. if localErr != nil {
  384. // 发送错误到通道,并由 errgroup 捕获
  385. // errgroup 会处理第一个非nil错误,并取消其他 goroutine
  386. resultsChan <- CombinedResult{Id: currentID, Err: fmt.Errorf("GetWebForwarding for id %d failed: %w", currentID, localErr)}
  387. return localErr // 返回错误给 errgroup
  388. }
  389. if wf == nil { // 正常情况下,如果没错误,wf不应为nil,但防御性检查
  390. localErr = fmt.Errorf("GetWebForwarding for id %d returned nil data without error", currentID)
  391. resultsChan <- CombinedResult{Id: currentID, Err: localErr}
  392. return localErr
  393. }
  394. // 2. 获取 Backend IP 信息
  395. // 注意:这里我们允许 GetWebForwardingIpsByID 可能返回 nil 数据(例如没有规则)而不是错误
  396. // 如果它也可能返回错误,则处理方式与上面类似
  397. bk, localErr = s.webForwardingRepository.GetWebForwardingIpsByID(gCtx, currentID)
  398. if localErr != nil {
  399. // 如果获取IP信息失败是一个致命错误,则也应返回错误
  400. // 如果允许部分成功(比如有WebForwarding但没有IP信息),则可以不将此视为errgroup的错误
  401. // 这里假设它也是一个需要errgroup捕获的错误
  402. resultsChan <- CombinedResult{Id: currentID, Forwarding: wf, Err: fmt.Errorf("GetWebForwardingIpsByID for id %d failed: %w", currentID, localErr)}
  403. return localErr // 返回错误给 errgroup
  404. }
  405. // bk 可能是 nil 如果没有错误且没有规则,这取决于业务逻辑
  406. // 发送成功的结果到通道
  407. resultsChan <- CombinedResult{Id: currentID, Forwarding: wf, BackendRule: bk}
  408. return nil // 此goroutine成功
  409. })
  410. }
  411. // 等待所有goroutine完成
  412. groupErr := g.Wait()
  413. // 关闭通道,表示所有发送者都已完成
  414. // 这一步很重要,这样下面的 range 循环才能正常结束
  415. close(resultsChan)
  416. // 如果 errgroup 捕获到任何错误,优先返回该错误
  417. if groupErr != nil {
  418. // 虽然errgroup已经出错了,但通道中可能已经有一些结果(来自出错前成功或出错的goroutine)
  419. // 我们需要排空通道以避免goroutine泄漏(如果它们在发送时阻塞)
  420. // 但由于我们优先返回groupErr,这些结果将被丢弃。
  421. // 在这种设计下,通常任何一个子任务失败都会导致整个操作失败。
  422. return nil, groupErr
  423. }
  424. // 如果没有错误,收集所有成功的结果
  425. finalResults := make([]v1.WebForwardingDataRequest, 0, len(ids))
  426. for res := range resultsChan {
  427. // 再次检查通道中的错误,尽管 errgroup 应该已经捕获了
  428. // 但这是一种更细致的错误处理,以防万一有goroutine在errgroup.Wait()前发送了错误但未被errgroup捕获
  429. // (理论上,如果goroutine返回了错误,errgroup会处理)
  430. // 主要目的是处理 res.forwarding 为 nil 的情况 (如果上面允许不返回错误)
  431. if res.Err != nil {
  432. // 如果到这里还有错误,说明逻辑可能有问题,或者我们决定忽略某些类型的子错误
  433. // 在此示例中,因为 g.Wait() 没有错误,所以这里的 res.err 应该是nil
  434. // 如果不是,那么可能是goroutine在return nil前发送了带有错误的res。
  435. // 严格来说,如果errgroup没有错误,这里res.err也应该是nil
  436. // 但以防万一,我们可以记录日志
  437. return nil, fmt.Errorf("received error from goroutine for ID %d: %w", res.Id, res.Err)
  438. }
  439. if res.Forwarding == nil {
  440. return nil, fmt.Errorf("received nil forwarding from goroutine for ID %d", res.Id)
  441. }
  442. dataReq := v1.WebForwardingDataRequest{
  443. Id: res.Forwarding.Id,
  444. Port: res.Forwarding.Port,
  445. Domain: res.Forwarding.Domain,
  446. CustomHost: res.Forwarding.CustomHost,
  447. CcCount: res.Forwarding.CcCount,
  448. CcDuration: res.Forwarding.CcDuration,
  449. CcBlockCount: res.Forwarding.CcBlockCount,
  450. CcBlockDuration: res.Forwarding.CcBlockDuration,
  451. Cc4xxCount: res.Forwarding.Cc4xxCount,
  452. Cc4xxDuration: res.Forwarding.Cc4xxDuration,
  453. Cc4xxBlockCount: res.Forwarding.Cc4xxBlockCount,
  454. Cc4xxBlockDuration: res.Forwarding.Cc4xxBlockDuration,
  455. Cc5xxCount: res.Forwarding.Cc5xxCount,
  456. Cc5xxDuration: res.Forwarding.Cc5xxDuration,
  457. Cc5xxBlockCount: res.Forwarding.Cc5xxBlockCount,
  458. Cc5xxBlockDuration: res.Forwarding.Cc5xxBlockDuration,
  459. IsHttps: res.Forwarding.IsHttps,
  460. Comment: res.Forwarding.Comment,
  461. HttpsKey: res.Forwarding.HttpsKey,
  462. HttpsCert: res.Forwarding.HttpsCert,
  463. }
  464. if res.BackendRule != nil { // 只有当 BackendRule 存在时才填充相关字段
  465. dataReq.BackendList = res.BackendRule.BackendList
  466. dataReq.AllowIpList = res.BackendRule.AllowIpList
  467. dataReq.DenyIpList = res.BackendRule.DenyIpList
  468. dataReq.AccessRule = res.BackendRule.AccessRule
  469. }
  470. finalResults = append(finalResults, dataReq)
  471. }
  472. sort.Slice(finalResults, func(i, j int) bool {
  473. return finalResults[i].Id > finalResults[j].Id
  474. })
  475. return finalResults, nil
  476. }
  477. // publishDomainWhitelistTask is a helper function to publish domain whitelist tasks to RabbitMQ.
  478. // It can handle different actions like "add" or "del".
  479. func (s *webForwardingService) publishDomainWhitelistTask(domain, action string) {
  480. // Define message payload, including the action
  481. type domainTaskPayload struct {
  482. Domain string `json:"domain"`
  483. Action string `json:"action"`
  484. }
  485. payload := domainTaskPayload{
  486. Domain: domain,
  487. Action: action,
  488. }
  489. // Serialize the message
  490. msgBody, err := json.Marshal(payload)
  491. if err != nil {
  492. s.logger.Error("Failed to serialize domain whitelist task message", zap.Error(err), zap.String("domain", domain), zap.String("action", action))
  493. return
  494. }
  495. // Get task configuration
  496. taskCfg, ok := s.mq.GetTaskConfig("domain_whitelist")
  497. if !ok {
  498. s.logger.Error("Failed to get 'domain_whitelist' task configuration")
  499. return
  500. }
  501. // Construct the routing key dynamically based on the action
  502. routingKey := fmt.Sprintf("whitelist.domain.%s", action)
  503. // Construct the amqp.Publishing message
  504. publishingMsg := amqp.Publishing{
  505. ContentType: "application/json",
  506. Body: msgBody,
  507. DeliveryMode: amqp.Persistent, // Persistent message
  508. }
  509. // Publish the message
  510. err = s.mq.PublishWithCh(taskCfg.Exchange, routingKey, publishingMsg)
  511. if err != nil {
  512. s.logger.Error("Failed to publish domain whitelist task to MQ", zap.Error(err), zap.String("domain", domain), zap.String("action", action))
  513. } else {
  514. s.logger.Info("Successfully published domain whitelist task to MQ", zap.String("domain", domain), zap.String("action", action))
  515. }
  516. }