ZoneCloudflareServer.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  1. package server
  2. import (
  3. "bytes"
  4. "cfTest/cloudflareApi/zone"
  5. "context"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "github.com/cloudflare/cloudflare-go"
  10. "github.com/samber/lo"
  11. "io"
  12. "io/ioutil"
  13. "log"
  14. "net/http"
  15. "time"
  16. )
  17. type ZoneServer struct {
  18. zone.UnimplementedZoneCloudflareServer
  19. }
  20. type Subscription struct {
  21. ID string `json:"id"`
  22. RatePlan struct {
  23. ID string `json:"id"`
  24. PublicName string `json:"public_name"`
  25. Currency string `json:"currency"`
  26. Scope string `json:"scope"`
  27. ExternallyManaged bool `json:"externally_managed"`
  28. Sets []string `json:"sets"`
  29. IsContract bool `json:"is_contract"`
  30. } `json:"rate_plan"`
  31. ComponentValues []struct {
  32. Name string `json:"name"`
  33. Value int `json:"value"`
  34. Default int `json:"default,omitempty"`
  35. } `json:"component_values"`
  36. Zone struct {
  37. ID string `json:"id"`
  38. Name string `json:"name"`
  39. } `json:"zone"`
  40. Frequency string `json:"frequency"`
  41. Currency string `json:"currency"`
  42. Price int `json:"price"`
  43. Product struct {
  44. Name string `json:"name"`
  45. Period string `json:"period"`
  46. Billing string `json:"billing"`
  47. PublicName string `json:"public_name"`
  48. Duration int `json:"duration"`
  49. } `json:"product"`
  50. CancelAtPeriodEnd bool `json:"cancel_at_period_end"`
  51. CreatedDate time.Time `json:"created_date"`
  52. }
  53. var ArgoSubscriptionId = "argo_zone_ent_tryout"
  54. func (s *ZoneServer) GetArgoSettingSubscription(ctx context.Context, request *zone.IdRequest) (*zone.ArgoSetting, error) {
  55. log.Printf("apiKey Received: %v", request.GetApiKey())
  56. log.Printf("apiEmail Received: %v", request.GetApiEmail())
  57. log.Printf("zoneId Received: %v", request.GetZoneId())
  58. //设置HTTP请求
  59. client := &http.Client{}
  60. req, err := http.NewRequest("GET", "https://api.cloudflare.com/client/v4/zones/"+request.ZoneId+"/subscriptions", nil)
  61. if err != nil {
  62. return nil, err
  63. }
  64. req.Header.Add("X-Auth-Key", request.GetApiKey())
  65. req.Header.Add("X-Auth-Email", request.GetApiEmail())
  66. //执行HTTP请求
  67. resp, err := client.Do(req)
  68. if err != nil {
  69. return nil, err
  70. }
  71. defer func(Body io.ReadCloser) {
  72. _ = Body.Close()
  73. }(resp.Body)
  74. body, _ := ioutil.ReadAll(resp.Body)
  75. type ResponseType struct {
  76. Errors []interface{} `json:"errors"`
  77. Messages []interface{} `json:"messages"`
  78. Result []Subscription `json:"result"`
  79. ResultInfo struct {
  80. NextPage bool `json:"next_page"`
  81. } `json:"result_info"`
  82. Success bool `json:"success"`
  83. }
  84. var r ResponseType
  85. err = json.Unmarshal(body, &r)
  86. //处理返回逻辑
  87. if err != nil {
  88. return nil, fmt.Errorf("%s: %w", "error unmarshalling the JSON response", err)
  89. }
  90. if r.Success != true {
  91. return nil, fmt.Errorf("%s", r.Errors)
  92. }
  93. log.Printf("Response: %v", r)
  94. for _, v := range r.Result {
  95. if v.RatePlan.ID == ArgoSubscriptionId {
  96. return &zone.ArgoSetting{Enabled: true}, nil
  97. }
  98. }
  99. return &zone.ArgoSetting{Enabled: false}, nil
  100. }
  101. func (s *ZoneServer) CreateArgoSettingSubscription(ctx context.Context, request *zone.IdRequest) (*zone.ArgoSetting, error) {
  102. log.Printf("apiKey Received: %v", request.GetApiKey())
  103. log.Printf("apiEmail Received: %v", request.GetApiEmail())
  104. log.Printf("zoneId Received: %v", request.GetZoneId())
  105. type RequestType struct {
  106. RatePlan struct {
  107. ID string `json:"id"`
  108. } `json:"rate_plan"`
  109. Zone struct {
  110. ID string `json:"id"`
  111. Name string `json:"name"`
  112. } `json:"zone"`
  113. }
  114. type ResponseType struct {
  115. Errors []interface{} `json:"errors"`
  116. Messages []interface{} `json:"messages"`
  117. Result Subscription `json:"result"`
  118. Success bool `json:"success"`
  119. }
  120. bytesData, err := json.Marshal(RequestType{
  121. RatePlan: struct {
  122. ID string `json:"id"`
  123. }{
  124. ID: ArgoSubscriptionId,
  125. },
  126. Zone: struct {
  127. ID string `json:"id"`
  128. Name string `json:"name"`
  129. }{
  130. ID: request.ZoneId,
  131. },
  132. })
  133. if err != nil {
  134. return nil, err
  135. }
  136. //设置HTTP请求
  137. client := &http.Client{}
  138. req, err := http.NewRequest("POST", "https://api.cloudflare.com/client/v4/zones/"+request.ZoneId+"/subscription", bytes.NewReader(bytesData))
  139. if err != nil {
  140. return nil, err
  141. }
  142. req.Header.Add("X-Auth-Key", request.GetApiKey())
  143. req.Header.Add("X-Auth-Email", request.GetApiEmail())
  144. //执行HTTP请求
  145. resp, err := client.Do(req)
  146. if err != nil {
  147. return nil, err
  148. }
  149. defer func(Body io.ReadCloser) {
  150. _ = Body.Close()
  151. }(resp.Body)
  152. body, _ := ioutil.ReadAll(resp.Body)
  153. var r ResponseType
  154. err = json.Unmarshal(body, &r)
  155. //处理返回逻辑
  156. if err != nil {
  157. return nil, fmt.Errorf("%s: %w", "error unmarshalling the JSON response", err)
  158. }
  159. if r.Success != true {
  160. return nil, fmt.Errorf("%s", r.Errors)
  161. }
  162. log.Printf("Response: %v", r)
  163. if r.Result.RatePlan.ID == ArgoSubscriptionId {
  164. return &zone.ArgoSetting{Enabled: true}, nil
  165. }
  166. return &zone.ArgoSetting{Enabled: false}, nil
  167. }
  168. func (s *ZoneServer) UpdateArgoSetting(ctx context.Context, requestCloudflare *zone.UpdateArgoRequestCloudflare) (*zone.ArgoSetting, error) {
  169. log.Printf("apiKey Received: %v", requestCloudflare.GetApiKey())
  170. log.Printf("apiEmail Received: %v", requestCloudflare.GetApiEmail())
  171. log.Printf("zoneId Received: %v", requestCloudflare.GetZoneId())
  172. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  173. if err != nil {
  174. return nil, err
  175. }
  176. settingValue := Proto2GoArgoSetting(requestCloudflare.GetArgoSetting())
  177. setting, err := api.UpdateArgoSmartRouting(ctx, requestCloudflare.ZoneId, settingValue)
  178. if err != nil {
  179. return nil, err
  180. }
  181. return Go2ProtoArgoSetting(setting.Value), nil
  182. }
  183. func (s *ZoneServer) GetArgoSetting(ctx context.Context, requestCloudflare *zone.IdRequest) (*zone.ArgoSetting, error) {
  184. log.Printf("apiKey Received: %v", requestCloudflare.GetApiKey())
  185. log.Printf("apiEmail Received: %v", requestCloudflare.GetApiEmail())
  186. log.Printf("zoneId Received: %v", requestCloudflare.GetZoneId())
  187. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  188. if err != nil {
  189. return nil, err
  190. }
  191. setting, err := api.ArgoSmartRouting(ctx, requestCloudflare.ZoneId)
  192. if err != nil {
  193. return nil, err
  194. }
  195. return Go2ProtoArgoSetting(setting.Value), nil
  196. }
  197. func (s *ZoneServer) ZoneIDByNameCloudflare(ctx context.Context, requestCloudflare *zone.ZoneIDByNameRequestCloudflare) (*zone.ZoneIDByNameReplyCloudflare, error) {
  198. log.Printf("apiKey Received: %v", requestCloudflare.GetApiKey())
  199. log.Printf("apiEmail Received: %v", requestCloudflare.GetApiEmail())
  200. log.Printf("zoneName Received: %v", requestCloudflare.GetZoneName())
  201. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  202. if err != nil {
  203. return nil, err
  204. }
  205. id, err := api.ZoneIDByName(requestCloudflare.ZoneName)
  206. if err != nil {
  207. return nil, err
  208. }
  209. return &zone.ZoneIDByNameReplyCloudflare{ZoneId: id}, err
  210. }
  211. func (s *ZoneServer) ZoneDetails(ctx context.Context, requestCloudflare *zone.ZoneDetailsRequestCloudflare) (*zone.ZoneDetailsReplyCloudflare, error) {
  212. log.Printf("apiKey Received: %v", requestCloudflare.GetApiKey())
  213. log.Printf("apiEmail Received: %v", requestCloudflare.GetApiEmail())
  214. log.Printf("zoneId Received: %v", requestCloudflare.GetZoneId())
  215. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  216. if err != nil {
  217. return nil, err
  218. }
  219. ctxAPI := context.Background()
  220. details, err := api.ZoneDetails(ctxAPI, requestCloudflare.GetZoneId())
  221. if err != nil {
  222. return nil, err
  223. }
  224. return &zone.ZoneDetailsReplyCloudflare{
  225. Result: Go2ProtoZone(details),
  226. }, err
  227. }
  228. func (s *ZoneServer) GetZones(ctx context.Context, requestCloudflare *zone.GetZonesRequestCloudflare) (*zone.GetZonesReplyCloudflare, error) {
  229. log.Printf("apiKey Received: %v", requestCloudflare.GetApiKey())
  230. log.Printf("apiEmail Received: %v", requestCloudflare.GetApiEmail())
  231. log.Printf("domain Received: %v", requestCloudflare.GetDomain())
  232. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  233. if err != nil {
  234. return nil, err
  235. }
  236. details, err := api.ListZones(ctx, "name", requestCloudflare.GetDomain())
  237. if err != nil {
  238. return nil, err
  239. }
  240. list := make([]*zone.ZoneCloudflareEntity, len(details))
  241. for i, detail := range details {
  242. list[i] = Go2ProtoZone(detail)
  243. }
  244. return &zone.GetZonesReplyCloudflare{
  245. Result: list,
  246. Success: true,
  247. }, err
  248. }
  249. func (s *ZoneServer) ListZones(ctx context.Context, requestCloudflare *zone.ListZonesRequestCloudflare) (*zone.ZonesList, error) {
  250. log.Printf("apiKey Received: %v", requestCloudflare.GetApiKey())
  251. log.Printf("apiEmail Received: %v", requestCloudflare.GetApiEmail())
  252. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  253. if err != nil {
  254. return nil, err
  255. }
  256. ctxAPI := context.Background()
  257. details, err := api.ListZones(ctxAPI)
  258. if err != nil {
  259. return nil, err
  260. }
  261. list := make([]*zone.ZoneCloudflareEntity, len(details))
  262. for i, detail := range details {
  263. list[i] = Go2ProtoZone(detail)
  264. }
  265. return &zone.ZonesList{
  266. Result: list,
  267. }, err
  268. }
  269. func (s *ZoneServer) ListZonesByAccountId(ctx context.Context, requestCloudflare *zone.ListZonesByAccountIdRequestCloudflare) (*zone.ZonesList, error) {
  270. log.Printf("apiKey Received: %v", requestCloudflare.GetApiKey())
  271. log.Printf("apiEmail Received: %v", requestCloudflare.GetApiEmail())
  272. log.Printf("accountId Received: %v", requestCloudflare.GetAccountId())
  273. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  274. if err != nil {
  275. return nil, err
  276. }
  277. ctxAPI := context.Background()
  278. opt := cloudflare.WithZoneFilters("", requestCloudflare.AccountId, "")
  279. details, err := api.ListZonesContext(ctxAPI, opt)
  280. if err != nil {
  281. return nil, err
  282. }
  283. list := make([]*zone.ZoneCloudflareEntity, len(details.Result))
  284. for i, detail := range details.Result {
  285. list[i] = Go2ProtoZone(detail)
  286. }
  287. return &zone.ZonesList{
  288. Result: list,
  289. }, err
  290. }
  291. func (s *ZoneServer) EditZone(ctx context.Context, requestCloudflare *zone.EditZoneRequestCloudflare) (*zone.EditZoneReplyCloudflare, error) {
  292. log.Printf("apiKey Received: %v", requestCloudflare.GetApiKey())
  293. log.Printf("apiEmail Received: %v", requestCloudflare.GetApiEmail())
  294. log.Printf("zoneId Received: %v", requestCloudflare.GetZoneId())
  295. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  296. if err != nil {
  297. return nil, err
  298. }
  299. ctxAPI := context.Background()
  300. opts := cloudflare.ZoneOptions{}
  301. opts.Paused = requestCloudflare.Paused
  302. if requestCloudflare.PlanId != nil {
  303. opts.Plan = &cloudflare.ZonePlan{
  304. ZonePlanCommon: cloudflare.ZonePlanCommon{
  305. ID: requestCloudflare.GetPlanId(),
  306. },
  307. }
  308. }
  309. if requestCloudflare.Type != nil {
  310. opts.Type = requestCloudflare.GetType()
  311. }
  312. editZone, err := api.EditZone(ctxAPI, requestCloudflare.GetZoneId(), opts)
  313. if err != nil {
  314. return nil, err
  315. }
  316. return &zone.EditZoneReplyCloudflare{
  317. Result: Go2ProtoZone(editZone),
  318. Success: true,
  319. }, nil
  320. }
  321. func (s *ZoneServer) DeleteZone(ctx context.Context, requestCloudflare *zone.DeleteZoneRequestCloudflare) (*zone.DeleteZoneReplyCloudflare, error) {
  322. log.Printf("apiKey Received: %v", requestCloudflare.GetApiKey())
  323. log.Printf("apiEmail Received: %v", requestCloudflare.GetApiEmail())
  324. log.Printf("zoneId Received: %v", requestCloudflare.GetZoneId())
  325. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  326. if err != nil {
  327. return nil, err
  328. }
  329. ctxAPI := context.Background()
  330. deleteZone, err := api.DeleteZone(ctxAPI, requestCloudflare.GetZoneId())
  331. if err != nil {
  332. return nil, err
  333. }
  334. return &zone.DeleteZoneReplyCloudflare{
  335. Success: true,
  336. Id: deleteZone.ID,
  337. }, nil
  338. }
  339. func (s *ZoneServer) ActivationCheck(ctx context.Context, requestCloudflare *zone.ActivationCheckRequestCloudflare) (*zone.ActivationCheckReplyCloudflare, error) {
  340. log.Printf("apiKey Received: %v", requestCloudflare.GetApiKey())
  341. log.Printf("apiEmail Received: %v", requestCloudflare.GetApiEmail())
  342. log.Printf("zoneId Received: %v", requestCloudflare.GetZoneId())
  343. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  344. if err != nil {
  345. return nil, err
  346. }
  347. ctxAPI := context.Background()
  348. activationCheck, err := api.ZoneActivationCheck(ctxAPI, requestCloudflare.GetZoneId())
  349. if err != nil {
  350. return nil, err
  351. }
  352. return &zone.ActivationCheckReplyCloudflare{
  353. Success: activationCheck.Success,
  354. }, nil
  355. }
  356. var phaseMap = map[zone.Phase]string{
  357. zone.Phase_http_request_sanitize: "http_request_sanitize",
  358. zone.Phase_http_request_transform: "http_request_transform",
  359. //zone.Phase_http_request_origin: "http_request_origin",
  360. //zone.Phase_http_request_cache_settings: "http_request_cache_settings",
  361. //zone.Phase_http_config_settings: "http_config_settings",
  362. //zone.Phase_http_request_dynamic_redirect: "http_request_dynamic_redirect",
  363. //zone.Phase_ddos_l7: "ddos_l7",
  364. //zone.Phase_http_request_firewall_custom: "http_request_firewall_custom",
  365. //zone.Phase_http_ratelimit: "http_ratelimit",
  366. //zone.Phase_http_request_firewall_managed: "http_request_firewall_managed",
  367. //zone.Phase_http_request_sbfm: "http_request_sbfm",
  368. //zone.Phase_http_request_redirect: "http_request_redirect",
  369. zone.Phase_http_request_late_transform: "http_request_late_transform",
  370. //zone.Phase_http_custom_errors: "http_custom_errors",
  371. zone.Phase_http_response_headers_transform: "http_response_headers_transform",
  372. //zone.Phase_http_response_firewall_managed: "http_response_firewall_managed",
  373. //zone.Phase_http_log_custom_fields: "http_log_custom_fields",
  374. }
  375. func (s *ZoneServer) GetRuleSet(ctx context.Context, requestCloudflare *zone.GetRuleSetRequestCloudflare) (*zone.RuleList, error) {
  376. api, err := cloudflare.New(requestCloudflare.ApiKey, requestCloudflare.ApiEmail)
  377. if err != nil {
  378. return nil, err
  379. }
  380. ctxAPI := context.Background()
  381. switch phaseMap[requestCloudflare.Phase] {
  382. case "http_request_transform", "http_request_late_transform", "http_response_headers_transform":
  383. default:
  384. return nil, errors.New("未定义规则阶段")
  385. }
  386. ruleset, err := api.GetZoneRulesetPhase(ctxAPI, requestCloudflare.ZoneId, phaseMap[requestCloudflare.Phase])
  387. if err != nil {
  388. _, ok := err.(*cloudflare.NotFoundError)
  389. if ok {
  390. ruleset.Rules = make([]cloudflare.RulesetRule, 0)
  391. err = nil
  392. } else {
  393. return nil, err
  394. }
  395. }
  396. filterMap := lo.FilterMap[cloudflare.RulesetRule, *zone.Rule](ruleset.Rules, func(rule cloudflare.RulesetRule, _ int) (*zone.Rule, bool) {
  397. phase, err := Go2ProtoRuleRuleByPhase(&rule, ruleset.Phase)
  398. if err != nil {
  399. return nil, false
  400. }
  401. return phase, true
  402. })
  403. return &zone.RuleList{Rules: filterMap}, nil
  404. }
  405. func (s *ZoneServer) UpdateRuleSet(ctx context.Context, requestCloudflare *zone.UpdateRuleSetRequestCloudflare) (*zone.RuleList, error) {
  406. api, err := cloudflare.New(requestCloudflare.ApiKey, requestCloudflare.ApiEmail)
  407. if err != nil {
  408. return nil, err
  409. }
  410. ctxAPI := context.Background()
  411. phase := phaseMap[requestCloudflare.Phase]
  412. filterMap := lo.FilterMap[*zone.Rule, cloudflare.RulesetRule](requestCloudflare.Rules, func(rule *zone.Rule, index int) (cloudflare.RulesetRule, bool) {
  413. ruleResult, err := Proto2GoRulesetRuleByPhase(rule, requestCloudflare.Phase)
  414. if err != nil || ruleResult == nil {
  415. return cloudflare.RulesetRule{}, false
  416. }
  417. return *ruleResult, true
  418. })
  419. //for _, rule := range requestCloudflare.Rules {
  420. // ruleResult, err := Proto2GoRulesetRuleByPhase(rule, requestCloudflare.Phase)
  421. // if err != nil {
  422. // return nil, err
  423. // }
  424. // if ruleResult != nil {
  425. // ruleSet.Rules = append(ruleSet.Rules, *ruleResult)
  426. // }
  427. //}
  428. ruleset, err := api.UpdateZoneRulesetPhase(ctxAPI, requestCloudflare.ZoneId, phase, cloudflare.Ruleset{
  429. Rules: filterMap,
  430. })
  431. if err != nil {
  432. return nil, err
  433. }
  434. rulesReturn := lo.FilterMap[cloudflare.RulesetRule, *zone.Rule](ruleset.Rules, func(rule cloudflare.RulesetRule, _ int) (*zone.Rule, bool) {
  435. ruleReturn, err := Go2ProtoRuleRuleByPhase(&rule, ruleset.Phase)
  436. if err != nil {
  437. return nil, false
  438. }
  439. return ruleReturn, true
  440. })
  441. //var rulesReturn []*zone.Rule
  442. //for _, rule := range rulesetResult.Rules {
  443. // ruleReturn, err := Go2ProtoRuleRuleByPhase(&rule, rulesetResult.Phase)
  444. // if err != nil {
  445. // return nil, err
  446. // }
  447. // if ruleReturn != nil {
  448. // rulesReturn = append(rulesReturn, ruleReturn)
  449. // }
  450. //}
  451. return &zone.RuleList{Rules: rulesReturn}, nil
  452. }
  453. //func UpdateRuleSet(apiKey, apiEmail, zoneID, rulesetPhase string, ruleset cloudflare.Ruleset) (*cloudflare.Ruleset, error) {
  454. // api, err := cloudflare.New(apiKey, apiEmail)
  455. // if err != nil {
  456. // return nil, err
  457. // }
  458. // ctxAPI := context.Background()
  459. // phase, err := api.UpdateZoneRulesetPhase(ctxAPI, zoneID, rulesetPhase, ruleset)
  460. // if err != nil {
  461. // return nil, err
  462. // }
  463. // return &phase, nil
  464. //}
  465. //PageRule CURD
  466. func (s *ZoneServer) ListPageRule(ctx context.Context, requestCloudflare *zone.ListPageRuleRequestCloudflare) (*zone.PageRuleList, error) {
  467. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  468. if err != nil {
  469. return nil, err
  470. }
  471. ctxAPI := context.Background()
  472. rules, err := api.ListPageRules(ctxAPI, requestCloudflare.GetZoneId())
  473. if err != nil {
  474. return nil, err
  475. }
  476. filterMap := lo.FilterMap[cloudflare.PageRule, *zone.PageRule](rules, func(rule cloudflare.PageRule, _ int) (*zone.PageRule, bool) {
  477. pageRule := Go2ProtoPageRule(&rule)
  478. return pageRule, true
  479. })
  480. return &zone.PageRuleList{PageRules: filterMap}, nil
  481. }
  482. func (s *ZoneServer) CreatePageRule(ctx context.Context, requestCloudflare *zone.CreatePageRuleRequestCloudflare) (*zone.PageRule, error) {
  483. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  484. if err != nil {
  485. return nil, err
  486. }
  487. ctxAPI := context.Background()
  488. rule, err := Proto2GoPageRule(requestCloudflare.PageRule)
  489. if err != nil {
  490. return nil, err
  491. }
  492. pageRule, err := api.CreatePageRule(ctxAPI, requestCloudflare.GetZoneId(), *rule)
  493. if err != nil {
  494. return nil, err
  495. }
  496. return Go2ProtoPageRule(pageRule), nil
  497. }
  498. func (s *ZoneServer) UpdatePageRule(ctx context.Context, requestCloudflare *zone.UpdatePageRuleRequestCloudflare) (*zone.PageRule, error) {
  499. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  500. if err != nil {
  501. return nil, err
  502. }
  503. ctxAPI := context.Background()
  504. rule, err := Proto2GoPageRule(requestCloudflare.PageRule)
  505. if err != nil {
  506. return nil, err
  507. }
  508. err = api.UpdatePageRule(ctxAPI, requestCloudflare.GetZoneId(), rule.ID, *rule)
  509. if err != nil {
  510. return nil, err
  511. }
  512. return requestCloudflare.PageRule, nil
  513. }
  514. func (s *ZoneServer) DeletePageRule(ctx context.Context, requestCloudflare *zone.DeletePageRuleRequestCloudflare) (*zone.PageRule, error) {
  515. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  516. if err != nil {
  517. return nil, err
  518. }
  519. ctxAPI := context.Background()
  520. err = api.DeletePageRule(ctxAPI, requestCloudflare.ZoneId, requestCloudflare.PageRuleId)
  521. if err != nil {
  522. return nil, err
  523. }
  524. return &zone.PageRule{}, nil
  525. }
  526. //func UpdatePageRule(apiKey, apiEmail, zoneID string, rule *zone.PageRule) (*zone.PageRule, error) {
  527. // api, err := cloudflare.New(apiKey, apiEmail)
  528. // if err != nil {
  529. // return nil, err
  530. // }
  531. //
  532. // ctxAPI := context.Background()
  533. // goPageRule, err := Proto2GoPageRule(rule)
  534. // if err != nil {
  535. // return nil, err
  536. // }
  537. // pageRule, err := api.CreatePageRule(ctxAPI, zoneID, *goPageRule)
  538. // if err != nil {
  539. // return nil, err
  540. // }
  541. //
  542. // protoPageRule := Go2ProtoPageRule(pageRule)
  543. //
  544. // return protoPageRule, nil
  545. //}
  546. type PageRuleActionCacheKeyFieldsQueryString struct {
  547. Exclude interface{} `json:"exclude"`
  548. Include interface{} `json:"include"`
  549. }
  550. type PageRuleActionCacheKeyFields struct {
  551. QueryString PageRuleActionCacheKeyFieldsQueryString `json:"query_string"`
  552. }
  553. type UpdatePageRulesPrioritiesStruct struct {
  554. Id string `json:"id"`
  555. Priority int `json:"priority"`
  556. }
  557. func (s *ZoneServer) UpdatePageRulesPriorities(ctx context.Context, requestCloudflare *zone.UpdatePageRulesPrioritiesRequestCloudflare) (*zone.PageRuleList, error) {
  558. //TODO 参数检查
  559. //设置HTTP请求
  560. client := &http.Client{}
  561. bytesData, err := json.Marshal(requestCloudflare.Data)
  562. if err != nil {
  563. return nil, err
  564. }
  565. req, err := http.NewRequest("PUT", "https://api.cloudflare.com/client/v4/zones/"+requestCloudflare.ZoneId+"/pagerules/priorities", bytes.NewReader(bytesData))
  566. if err != nil {
  567. return nil, err
  568. }
  569. req.Header.Add("X-Auth-Key", requestCloudflare.GetApiKey())
  570. req.Header.Add("X-Auth-Email", requestCloudflare.GetApiEmail())
  571. //执行HTTP请求
  572. resp, err := client.Do(req)
  573. if err != nil {
  574. return nil, err
  575. }
  576. defer func(Body io.ReadCloser) {
  577. _ = Body.Close()
  578. }(resp.Body)
  579. body, _ := ioutil.ReadAll(resp.Body)
  580. //解析HTTP返回数据
  581. var r cloudflare.PageRulesResponse
  582. err = json.Unmarshal(body, &r)
  583. //处理返回逻辑
  584. if err != nil {
  585. return nil, fmt.Errorf("%s: %w", "error unmarshalling the JSON response", err)
  586. }
  587. if r.Success != true {
  588. return nil, fmt.Errorf("%s", r.Errors)
  589. }
  590. rules := r.Result
  591. filterMap := lo.FilterMap[cloudflare.PageRule, *zone.PageRule](rules, func(rule cloudflare.PageRule, _ int) (*zone.PageRule, bool) {
  592. pageRule := Go2ProtoPageRule(&rule)
  593. return pageRule, true
  594. })
  595. return &zone.PageRuleList{PageRules: filterMap}, nil
  596. }