package server import ( "cfTest/cloudflareApi/loadBalancer" "context" "github.com/cloudflare/cloudflare-go" "github.com/jinzhu/copier" "github.com/samber/lo" ) type LoadBalancerServer struct { loadBalancer.UnimplementedLoadBalancerCloudflareServer } func Go2ProtoLoadBalancer(goBalancer *cloudflare.LoadBalancer) (protoBalancer *loadBalancer.LoadBalancer) { protoBalancer = new(loadBalancer.LoadBalancer) err := copier.Copy(protoBalancer, goBalancer) if err != nil { return nil } protoBalancer.Id = goBalancer.ID return } func Proto2GoLoadBalancer(protoBalancer *loadBalancer.LoadBalancer) (goBalancer *cloudflare.LoadBalancer) { goBalancer = new(cloudflare.LoadBalancer) err := copier.Copy(goBalancer, protoBalancer) if err != nil { return nil } goBalancer.ID = protoBalancer.Id return } func (d LoadBalancerServer) List(ctx context.Context, request *loadBalancer.ListRequest) (*loadBalancer.LoadBalancerList, error) { api, err := cloudflare.New(request.GetApiKey(), request.GetApiEmail()) if err != nil { return nil, err } ctxAPI := context.Background() balancers, err := api.ListLoadBalancers(ctxAPI, request.ZoneId) if err != nil { return nil, err } filterMap := lo.FilterMap[cloudflare.LoadBalancer, *loadBalancer.LoadBalancer](balancers, func(balancer cloudflare.LoadBalancer, _ int) (*loadBalancer.LoadBalancer, bool) { protoLoadBalancer := Go2ProtoLoadBalancer(&balancer) if protoLoadBalancer == nil { return nil, false } return protoLoadBalancer, true }) return &loadBalancer.LoadBalancerList{LoadBalancers: filterMap}, nil } func (d LoadBalancerServer) Create(ctx context.Context, request *loadBalancer.LoadBalancerRequest) (*loadBalancer.LoadBalancer, error) { api, err := cloudflare.New(request.GetApiKey(), request.GetApiEmail()) if err != nil { return nil, err } ctxAPI := context.Background() in := Proto2GoLoadBalancer(request.LoadBalancer) balancer, err := api.CreateLoadBalancer(ctxAPI, request.ZoneId, *in) if err != nil { return nil, err } out := Go2ProtoLoadBalancer(&balancer) return out, nil } func (d LoadBalancerServer) Update(ctx context.Context, request *loadBalancer.LoadBalancerRequest) (*loadBalancer.LoadBalancer, error) { api, err := cloudflare.New(request.GetApiKey(), request.GetApiEmail()) if err != nil { return nil, err } ctxAPI := context.Background() in := Proto2GoLoadBalancer(request.LoadBalancer) balancer, err := api.ModifyLoadBalancer(ctxAPI, request.ZoneId, *in) if err != nil { return nil, err } out := Go2ProtoLoadBalancer(&balancer) return out, nil } func (d LoadBalancerServer) Delete(ctx context.Context, request *loadBalancer.DeleteRequest) (*loadBalancer.Empty, error) { api, err := cloudflare.New(request.GetApiKey(), request.GetApiEmail()) if err != nil { return nil, err } ctxAPI := context.Background() err = api.DeleteLoadBalancer(ctxAPI, request.ZoneId, request.Id) if err != nil { return nil, err } return &loadBalancer.Empty{}, nil }