From a63fd499143b96d7fa46af8c1d3d65381bebffdf Mon Sep 17 00:00:00 2001 From: TangBin Date: Thu, 25 Oct 2018 16:28:37 +0800 Subject: [PATCH] add fill struct method --- pkg/util/aws/instance.go | 9 +++++---- pkg/util/aws/utils.go | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/pkg/util/aws/instance.go b/pkg/util/aws/instance.go index f79b88f4ad..0a9b4b09a3 100644 --- a/pkg/util/aws/instance.go +++ b/pkg/util/aws/instance.go @@ -390,7 +390,8 @@ func (self *SRegion) GetInstances(zoneId string, ids []string, offset int, limit instances := []SInstance{} for _, reservation := range res.Reservations { for _, instance := range reservation.Instances { - instanceType, err := self.GetInstanceType(StrVal(instance.InstanceType)) + FillZero(instance) + instanceType, err := self.GetInstanceType(*instance.InstanceType) if err != nil { return nil, 0 , err } @@ -415,9 +416,9 @@ func (self *SRegion) GetInstances(zoneId string, ids []string, offset int, limit var networkInterfaces SNetworkInterfaces for _, n := range instance.NetworkInterfaces { i := SNetworkInterface{ - MacAddress: StrVal(n.MacAddress), - NetworkInterfaceId: StrVal(n.NetworkInterfaceId), - PrimaryIpAddress: StrVal(n.PrivateIpAddress), + MacAddress: *n.MacAddress, + NetworkInterfaceId: *n.NetworkInterfaceId, + PrimaryIpAddress: *n.PrivateIpAddress, } networkInterfaces.NetworkInterface = append(networkInterfaces.NetworkInterface, i) } diff --git a/pkg/util/aws/utils.go b/pkg/util/aws/utils.go index 27ade4385f..34abc742da 100644 --- a/pkg/util/aws/utils.go +++ b/pkg/util/aws/utils.go @@ -3,6 +3,7 @@ package aws import ( "fmt" "net" + "reflect" "strings" "github.com/aws/aws-sdk-go/service/ec2" @@ -311,4 +312,41 @@ func YunionSecRuleToAws(rule secrules.SecurityRule) ([]ec2.IpPermission, error) } return permissions, nil +} + + +// fill a pointer struct with zero value. +func FillZero(i interface{}) error { + V := reflect.Indirect(reflect.ValueOf(i)) + + if !V.CanSet() { + return fmt.Errorf("input is not addressable: %#v", i) + } + + if V.Kind() != reflect.Struct { + return fmt.Errorf("only accept struct type") + } + + for i := 0; i < V.NumField(); i++ { + field := V.Field(i) + + if field.Kind() == reflect.Ptr && field.IsNil() { + if field.CanSet() { + field.Set(reflect.New(field.Type().Elem())) + } + } + + vField := reflect.Indirect(field) + switch vField.Kind() { + case reflect.Map: + vField.Set(reflect.MakeMap(vField.Type())) + case reflect.Struct: + err := FillZero(field.Interface()) + if err != nil { + return err + } + } + } + + return nil } \ No newline at end of file