如何使Else消息只打印一次



在下面的代码中,如果用户输入错误的API名称以查找else语句;无法找到";消息,每次它经过apis.Items数组中的一个项目。但我只想打印一次错误信息。类似于在遍历CCD_ 3阵列中的所有项目之后,如果没有具有由用户提供的名称的项目;无法找到";消息我该如何做到这一点。Ps:我是这门语言的新手

for _, item := range apis.Items {
if item.Name == apiName {
fmt.Printf("API ID found: %+v ", item.Id)
api_id := item.Id 
cmd_2, err := exec.Command("aws", "apigateway", "get-export", "--rest-api-id", api_id, "--stage-name", stageName, "--export-type", "swagger", "/home/akshitha/Documents/" + apiName + ".json").Output()
if err != nil {
utils.HandleErrorAndExit("Error getting API swagger", err)
}
output := string(cmd_2[:])
fmt.Println(output)
break
}else {
fmt.Println("Unable to fine an API with the name " + apiName)
}

您可以在找到item时设置一个变量。如果没有找到,则printoutside循环。

像这样:

var found bool
for _, item := range apis.Items {
if item.Name == apiName {
fmt.Printf("API ID found: %+v ", item.Id)
api_id := item.Id
cmd_2, err := exec.Command("aws", "apigateway", "get-export", "--rest-api-id", api_id, "--stage-name", stageName, "--export-type", "swagger", "/home/akshitha/Documents/"+apiName+".json").Output()
if err != nil {
utils.HandleErrorAndExit("Error getting API swagger", err)
}
output := string(cmd_2[:])
fmt.Println(output)
found = true

break
}
}
if !found {
fmt.Println("Unable to fine an API with the name " + apiName)
}

最新更新