Go lang While循环

时间:2016-09-20 12:30:35

标签: go

  • 我想从AWS
  • 中提取所有自动缩放组
  • AWS在多个页面中提供响应,NextToken指向下一页。所以需要继续寻找NextToken并拉出群组名称
  • 如果没有NextToken,则退出。

在python中,我这样做:

import boto3
import pprint

session = boto3.session.Session(region_name='us-west-2')
client = session.client('autoscaling')

resp = client.describe_auto_scaling_groups()
pprint.pprint(resp)

while 'NextToken' in resp:
    resp = client.describe_auto_scaling_groups(NextToken=resp['NextToken'])          
    pprint.pprint(resp)

我在中遵循了类似的逻辑,并提出了以下代码:

package main

import (
    "fmt"
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/autoscaling"
)

func main() {
    sess, err := session.NewSession(&aws.Config{Region: aws.String("us-west-2")})

    if err != nil {
        fmt.Println("Failed to create session: ", sess)
        return
    }

    svc := autoscaling.New(sess)
    params := &autoscaling.DescribeAutoScalingGroupsInput{}
    resp, err := svc.DescribeAutoScalingGroups(params)

    if err != nil {
        fmt.Println("Something Went wrong")
        return
    }

    fmt.Println(resp)

    for {
        if resp.NextToken == nil {
            fmt.Println("No more pages left")
            break
        }

        params := &autoscaling.DescribeAutoScalingGroupsInput{
            NextToken: aws.String(*resp.NextToken),
        }
        resp, err := svc.DescribeAutoScalingGroups(params)

        if err != nil {
            fmt.Println("Something Went wrong")
            return
        }

        fmt.Println(resp)
    }
}

问题:我的代码转到第二页,然后继续循环到同一第二页。它不会进入第3页(当NextToken中有resp时)或者它没有退出(NextToken中没有resp时)。

在我的代码上寻求帮助。我正在学习

1 个答案:

答案 0 :(得分:2)

您的内心resp似乎shadow原来的resp。在内部 for循环(:=替换为=)中尝试此操作:

resp, err = svc.DescribeAutoScalingGroups(params)