我需要从Go SDK (https://docs.aws.amazon.com/sdk-for-go/api/service/apigateway/#Usage)中获得以下数据的值。我使用的是golang 1.17.
下面是lambda函数返回的数据。
Decoded Data: { map[]}
All the usage: map[4wxq8mcov8:[[0xc000353848 0xc000353870]]]
{
EndDate: "2021-08-31",
Items: {
4wxq8mcov8: [[12,975]]
},
StartDate: "2021-08-31",
UsagePlanId: "w4wuvt"
}
我只想要item: {api_key: [[this number, and this number]]}中的数据,并且我只想要数组中的两个数字。
示例返回数据,我想要12和975 -Items: { 4wxq8mcov8: [[12,975]] }
我如何获取数据,然后将两个数字除以得到百分比?获得百分比后,我将使用该数字与使用计划进行比较,以查看是否满足阈值。如果阈值为<=分割后的数字,我将通过SNS向slack或电子邮件发送消息。
现在我的重点是把数字从项目图中取出来。提前谢谢你。
package main
import (
"fmt"
"os"
"time"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/apigateway"
"github.com/mitchellh/mapstructure"
logging "github.com/sirupsen/logrus"
)
type UsageData struct {
APIKey string `mapstructure:"api_key"`
Value map[string][][]int64 `mapstructure:"values"`
}
func parseUsage(usage *apigateway.Usage) {
u := usage.Items
var data UsageData
err := mapstructure.Decode(u, &data)
if err != nil {
panic(err)
}
fmt.Println("Decoded Data: ", data)
fmt.Println("All the usage: ", u)
fmt.Println("Items value one %v and value two %v: ", u.Items.ValueOne, u.Items.ValueTwo)
}
func getUsagePlanInfo(client *apigateway.APIGateway) *apigateway.Usage {
currentDate := time.Now()
startDate := currentDate.Format("2006-01-02")
endDate := currentDate.Format("2006-01-02")
input := &apigateway.GetUsageInput{
UsagePlanId: aws.String(os.Getenv("USAGE_PLAN_ID")),
KeyId: aws.String(os.Getenv("API_KEY")),
StartDate: aws.String(startDate),
EndDate: aws.String(endDate),
}
results, _ := client.GetUsage(input)
logging.WithFields(logging.Fields{
"UsagePlanId EV": os.Getenv("USAGE_PLAN_ID"),
"KeyId EV": os.Getenv("API_KEY"),
"StartDate EV": startDate,
"EndDate EV": endDate,
"Usage Plan Info": results,
}).Info("Values")
//fmt.Println("Usage Plan Data: ", results.Items)
parseUsage(results)
return results
}
func handler() {
theSession := session.Must(session.NewSession())
srv := apigateway.New(theSession)
u := getUsagePlanInfo(srv)
fmt.Println(u)
}
func main() {
lambda.Start(handler)
}
要获得这两个数字,您必须从映射中获取它们。如果你总是知道键并且知道数组中只有一个元素你可以这样做
u := getUsagePlanInfo(srv)
items := u.Items
quota := *items["4wxq8mcov8"][0][0]
remaining := *items["4wxq8mcov8"][0][1]
为了更安全,你应该这样做
if item, ok := items["4wxq8mcov8"]; ok && len(item) > 0 && len(item[0]) > 1 {
quota := *item[0][0]
remaining := *item[0][1]
fmt.Printf("%d, %dn", quota, remaining)
}
如果你有多个键或者你不知道键,你必须迭代映射并获取每个键的值