ZoneCloudflareServer.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  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) CreateZone(ctx context.Context, requestCloudflare *zone.CreateZoneRequestCloudflare) (*zone.CreateZoneReplyCloudflare, error) {
  340. log.Printf("request Received: %+v", requestCloudflare)
  341. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  342. if err != nil {
  343. return nil, err
  344. }
  345. ctxAPI := context.Background()
  346. account, _, err := api.Account(ctxAPI, requestCloudflare.GetAccountId())
  347. if err != nil {
  348. return nil, err
  349. }
  350. createZone, err := api.CreateZone(ctxAPI, requestCloudflare.GetDomain(), false, account, "partial")
  351. if err != nil {
  352. return nil, err
  353. }
  354. return &zone.CreateZoneReplyCloudflare{
  355. Success: true,
  356. Id: createZone.ID,
  357. }, nil
  358. }
  359. func (s *ZoneServer) SetZonePlan(ctx context.Context, requestCloudflare *zone.SetZonePlanRequestCloudflare) (*zone.SetZonePlanReplyCloudflare, error) {
  360. log.Printf("request Received: %+v", requestCloudflare)
  361. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  362. if err != nil {
  363. return nil, err
  364. }
  365. ctxAPI := context.Background()
  366. err = api.ZoneSetPlan(ctxAPI, requestCloudflare.GetZoneId(), requestCloudflare.GetZonePlan())
  367. if err != nil {
  368. return nil, err
  369. }
  370. return &zone.SetZonePlanReplyCloudflare{
  371. Success: true,
  372. }, nil
  373. }
  374. func (s *ZoneServer) ActivationCheck(ctx context.Context, requestCloudflare *zone.ActivationCheckRequestCloudflare) (*zone.ActivationCheckReplyCloudflare, error) {
  375. log.Printf("apiKey Received: %v", requestCloudflare.GetApiKey())
  376. log.Printf("apiEmail Received: %v", requestCloudflare.GetApiEmail())
  377. log.Printf("zoneId Received: %v", requestCloudflare.GetZoneId())
  378. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  379. if err != nil {
  380. return nil, err
  381. }
  382. ctxAPI := context.Background()
  383. activationCheck, err := api.ZoneActivationCheck(ctxAPI, requestCloudflare.GetZoneId())
  384. if err != nil {
  385. return nil, err
  386. }
  387. return &zone.ActivationCheckReplyCloudflare{
  388. Success: activationCheck.Success,
  389. }, nil
  390. }
  391. var phaseMap = map[zone.Phase]string{
  392. zone.Phase_http_request_sanitize: "http_request_sanitize",
  393. zone.Phase_http_request_transform: "http_request_transform",
  394. //zone.Phase_http_request_origin: "http_request_origin",
  395. //zone.Phase_http_request_cache_settings: "http_request_cache_settings",
  396. //zone.Phase_http_config_settings: "http_config_settings",
  397. //zone.Phase_http_request_dynamic_redirect: "http_request_dynamic_redirect",
  398. //zone.Phase_ddos_l7: "ddos_l7",
  399. //zone.Phase_http_request_firewall_custom: "http_request_firewall_custom",
  400. //zone.Phase_http_ratelimit: "http_ratelimit",
  401. //zone.Phase_http_request_firewall_managed: "http_request_firewall_managed",
  402. //zone.Phase_http_request_sbfm: "http_request_sbfm",
  403. //zone.Phase_http_request_redirect: "http_request_redirect",
  404. zone.Phase_http_request_late_transform: "http_request_late_transform",
  405. //zone.Phase_http_custom_errors: "http_custom_errors",
  406. zone.Phase_http_response_headers_transform: "http_response_headers_transform",
  407. //zone.Phase_http_response_firewall_managed: "http_response_firewall_managed",
  408. //zone.Phase_http_log_custom_fields: "http_log_custom_fields",
  409. }
  410. func (s *ZoneServer) GetRuleSet(ctx context.Context, requestCloudflare *zone.GetRuleSetRequestCloudflare) (*zone.RuleList, error) {
  411. api, err := cloudflare.New(requestCloudflare.ApiKey, requestCloudflare.ApiEmail)
  412. if err != nil {
  413. return nil, err
  414. }
  415. ctxAPI := context.Background()
  416. switch phaseMap[requestCloudflare.Phase] {
  417. case "http_request_transform", "http_request_late_transform", "http_response_headers_transform":
  418. default:
  419. return nil, errors.New("未定义规则阶段")
  420. }
  421. ruleset, err := api.GetZoneRulesetPhase(ctxAPI, requestCloudflare.ZoneId, phaseMap[requestCloudflare.Phase])
  422. if err != nil {
  423. _, ok := err.(*cloudflare.NotFoundError)
  424. if ok {
  425. ruleset.Rules = make([]cloudflare.RulesetRule, 0)
  426. err = nil
  427. } else {
  428. return nil, err
  429. }
  430. }
  431. filterMap := lo.FilterMap[cloudflare.RulesetRule, *zone.Rule](ruleset.Rules, func(rule cloudflare.RulesetRule, _ int) (*zone.Rule, bool) {
  432. phase, err := Go2ProtoRuleRuleByPhase(&rule, ruleset.Phase)
  433. if err != nil {
  434. return nil, false
  435. }
  436. return phase, true
  437. })
  438. return &zone.RuleList{Rules: filterMap}, nil
  439. }
  440. func (s *ZoneServer) UpdateRuleSet(ctx context.Context, requestCloudflare *zone.UpdateRuleSetRequestCloudflare) (*zone.RuleList, error) {
  441. api, err := cloudflare.New(requestCloudflare.ApiKey, requestCloudflare.ApiEmail)
  442. if err != nil {
  443. return nil, err
  444. }
  445. ctxAPI := context.Background()
  446. phase := phaseMap[requestCloudflare.Phase]
  447. filterMap := lo.FilterMap[*zone.Rule, cloudflare.RulesetRule](requestCloudflare.Rules, func(rule *zone.Rule, index int) (cloudflare.RulesetRule, bool) {
  448. ruleResult, err := Proto2GoRulesetRuleByPhase(rule, requestCloudflare.Phase)
  449. if err != nil || ruleResult == nil {
  450. return cloudflare.RulesetRule{}, false
  451. }
  452. return *ruleResult, true
  453. })
  454. //for _, rule := range requestCloudflare.Rules {
  455. // ruleResult, err := Proto2GoRulesetRuleByPhase(rule, requestCloudflare.Phase)
  456. // if err != nil {
  457. // return nil, err
  458. // }
  459. // if ruleResult != nil {
  460. // ruleSet.Rules = append(ruleSet.Rules, *ruleResult)
  461. // }
  462. //}
  463. ruleset, err := api.UpdateZoneRulesetPhase(ctxAPI, requestCloudflare.ZoneId, phase, cloudflare.Ruleset{
  464. Rules: filterMap,
  465. })
  466. if err != nil {
  467. return nil, err
  468. }
  469. rulesReturn := lo.FilterMap[cloudflare.RulesetRule, *zone.Rule](ruleset.Rules, func(rule cloudflare.RulesetRule, _ int) (*zone.Rule, bool) {
  470. ruleReturn, err := Go2ProtoRuleRuleByPhase(&rule, ruleset.Phase)
  471. if err != nil {
  472. return nil, false
  473. }
  474. return ruleReturn, true
  475. })
  476. //var rulesReturn []*zone.Rule
  477. //for _, rule := range rulesetResult.Rules {
  478. // ruleReturn, err := Go2ProtoRuleRuleByPhase(&rule, rulesetResult.Phase)
  479. // if err != nil {
  480. // return nil, err
  481. // }
  482. // if ruleReturn != nil {
  483. // rulesReturn = append(rulesReturn, ruleReturn)
  484. // }
  485. //}
  486. return &zone.RuleList{Rules: rulesReturn}, nil
  487. }
  488. //func UpdateRuleSet(apiKey, apiEmail, zoneID, rulesetPhase string, ruleset cloudflare.Ruleset) (*cloudflare.Ruleset, error) {
  489. // api, err := cloudflare.New(apiKey, apiEmail)
  490. // if err != nil {
  491. // return nil, err
  492. // }
  493. // ctxAPI := context.Background()
  494. // phase, err := api.UpdateZoneRulesetPhase(ctxAPI, zoneID, rulesetPhase, ruleset)
  495. // if err != nil {
  496. // return nil, err
  497. // }
  498. // return &phase, nil
  499. //}
  500. //PageRule CURD
  501. func (s *ZoneServer) ListPageRule(ctx context.Context, requestCloudflare *zone.ListPageRuleRequestCloudflare) (*zone.PageRuleList, error) {
  502. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  503. if err != nil {
  504. return nil, err
  505. }
  506. ctxAPI := context.Background()
  507. rules, err := api.ListPageRules(ctxAPI, requestCloudflare.GetZoneId())
  508. if err != nil {
  509. return nil, err
  510. }
  511. filterMap := lo.FilterMap[cloudflare.PageRule, *zone.PageRule](rules, func(rule cloudflare.PageRule, _ int) (*zone.PageRule, bool) {
  512. pageRule := Go2ProtoPageRule(&rule)
  513. return pageRule, true
  514. })
  515. return &zone.PageRuleList{PageRules: filterMap}, nil
  516. }
  517. func (s *ZoneServer) CreatePageRule(ctx context.Context, requestCloudflare *zone.CreatePageRuleRequestCloudflare) (*zone.PageRule, error) {
  518. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  519. if err != nil {
  520. return nil, err
  521. }
  522. ctxAPI := context.Background()
  523. rule, err := Proto2GoPageRule(requestCloudflare.PageRule)
  524. if err != nil {
  525. return nil, err
  526. }
  527. pageRule, err := api.CreatePageRule(ctxAPI, requestCloudflare.GetZoneId(), *rule)
  528. if err != nil {
  529. return nil, err
  530. }
  531. return Go2ProtoPageRule(pageRule), nil
  532. }
  533. func (s *ZoneServer) UpdatePageRule(ctx context.Context, requestCloudflare *zone.UpdatePageRuleRequestCloudflare) (*zone.PageRule, error) {
  534. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  535. if err != nil {
  536. return nil, err
  537. }
  538. ctxAPI := context.Background()
  539. rule, err := Proto2GoPageRule(requestCloudflare.PageRule)
  540. if err != nil {
  541. return nil, err
  542. }
  543. err = api.UpdatePageRule(ctxAPI, requestCloudflare.GetZoneId(), rule.ID, *rule)
  544. if err != nil {
  545. return nil, err
  546. }
  547. return requestCloudflare.PageRule, nil
  548. }
  549. func (s *ZoneServer) DeletePageRule(ctx context.Context, requestCloudflare *zone.DeletePageRuleRequestCloudflare) (*zone.PageRule, error) {
  550. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  551. if err != nil {
  552. return nil, err
  553. }
  554. ctxAPI := context.Background()
  555. err = api.DeletePageRule(ctxAPI, requestCloudflare.ZoneId, requestCloudflare.PageRuleId)
  556. if err != nil {
  557. return nil, err
  558. }
  559. return &zone.PageRule{}, nil
  560. }
  561. //func UpdatePageRule(apiKey, apiEmail, zoneID string, rule *zone.PageRule) (*zone.PageRule, error) {
  562. // api, err := cloudflare.New(apiKey, apiEmail)
  563. // if err != nil {
  564. // return nil, err
  565. // }
  566. //
  567. // ctxAPI := context.Background()
  568. // goPageRule, err := Proto2GoPageRule(rule)
  569. // if err != nil {
  570. // return nil, err
  571. // }
  572. // pageRule, err := api.CreatePageRule(ctxAPI, zoneID, *goPageRule)
  573. // if err != nil {
  574. // return nil, err
  575. // }
  576. //
  577. // protoPageRule := Go2ProtoPageRule(pageRule)
  578. //
  579. // return protoPageRule, nil
  580. //}
  581. type PageRuleActionCacheKeyFieldsQueryString struct {
  582. Exclude interface{} `json:"exclude"`
  583. Include interface{} `json:"include"`
  584. }
  585. type PageRuleActionCacheKeyFields struct {
  586. QueryString PageRuleActionCacheKeyFieldsQueryString `json:"query_string"`
  587. }
  588. type UpdatePageRulesPrioritiesStruct struct {
  589. Id string `json:"id"`
  590. Priority int `json:"priority"`
  591. }
  592. func (s *ZoneServer) UpdatePageRulesPriorities(ctx context.Context, requestCloudflare *zone.UpdatePageRulesPrioritiesRequestCloudflare) (*zone.PageRuleList, error) {
  593. //TODO 参数检查
  594. //设置HTTP请求
  595. client := &http.Client{}
  596. bytesData, err := json.Marshal(requestCloudflare.Data)
  597. if err != nil {
  598. return nil, err
  599. }
  600. req, err := http.NewRequest("PUT", "https://api.cloudflare.com/client/v4/zones/"+requestCloudflare.ZoneId+"/pagerules/priorities", bytes.NewReader(bytesData))
  601. if err != nil {
  602. return nil, err
  603. }
  604. req.Header.Add("X-Auth-Key", requestCloudflare.GetApiKey())
  605. req.Header.Add("X-Auth-Email", requestCloudflare.GetApiEmail())
  606. //执行HTTP请求
  607. resp, err := client.Do(req)
  608. if err != nil {
  609. return nil, err
  610. }
  611. defer func(Body io.ReadCloser) {
  612. _ = Body.Close()
  613. }(resp.Body)
  614. body, _ := ioutil.ReadAll(resp.Body)
  615. //解析HTTP返回数据
  616. var r cloudflare.PageRulesResponse
  617. err = json.Unmarshal(body, &r)
  618. //处理返回逻辑
  619. if err != nil {
  620. return nil, fmt.Errorf("%s: %w", "error unmarshalling the JSON response", err)
  621. }
  622. if r.Success != true {
  623. return nil, fmt.Errorf("%s", r.Errors)
  624. }
  625. rules := r.Result
  626. filterMap := lo.FilterMap[cloudflare.PageRule, *zone.PageRule](rules, func(rule cloudflare.PageRule, _ int) (*zone.PageRule, bool) {
  627. pageRule := Go2ProtoPageRule(&rule)
  628. return pageRule, true
  629. })
  630. return &zone.PageRuleList{PageRules: filterMap}, nil
  631. }