How do I get the values out of the following – Items map[string][][]*int64 `locationName:"values" type:"map"` using Golang

huangapple go评论86阅读模式
英文:

How do I get the values out of the following - Items map[string][][]*int64 `locationName:"values" type:"map"` using Golang

问题

我需要从以下数据中获取值,该数据来自Go SDK(https://docs.aws.amazon.com/sdk-for-go/api/service/apigateway/#Usage)。我正在使用golang 1.17。

以下是我的lambda函数返回的数据。

解码后的数据:{ map[]}
所有的使用情况:map[4wxq8mcov8:[[0xc000353848 0xc000353870]]]
{
EndDate: "2021-08-31",
Items: {
4wxq8mcov8: [[12,975]]
},
StartDate: "2021-08-31",
UsagePlanId: "w4wuvt"
}

我只想要Items中的数据:{api_key: [[这个数字,和这个数字]]},我只想要数组中的两个数字。

例如返回的数据,我想要12和975 -
Items: { 4wxq8mcov8: [[12,975]] }

我应该如何获取这些数据,然后将这两个数字相除以获得百分比?一旦我获得了百分比,我将使用该数字与使用计划进行比较,以查看是否达到了阈值。如果阈值小于等于除以的数字,我将通过SNS发送消息到Slack或电子邮件。

现在我只关注从items map中获取数字。提前谢谢你。

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)
}
英文:

I need to get the values out of the following data that is from the Go SDK (<https://docs.aws.amazon.com/sdk-for-go/api/service/apigateway/#Usage>). I am using golang 1.17.

Below is the data returned by my lambda function.

Decoded Data:  { map[]}
All the usage:  map[4wxq8mcov8:[[0xc000353848 0xc000353870]]]
{
EndDate: &quot;2021-08-31&quot;,
Items: {
4wxq8mcov8: [[12,975]]
},
StartDate: &quot;2021-08-31&quot;,
UsagePlanId: &quot;w4wuvt&quot;
}

I only want the data from the Items: {api_key: [[this number, and this number]]}, and I only want the two numbers that are in the array.

Example return data and I want the 12 and the 975 -
Items: {
4wxq8mcov8: [[12,975]]
}

How do I go about getting the data and then dividing the two numbers to get a percentage? Once I get the percentage, I will use that number to compare against the usage plan to see if the threshold is met. If the threshold is <= the divided number, I will send a message via SNS to slack or an email.

Right now my focus is to get the numbers out of the items map. Thank you in advance.

  package main
import (
&quot;fmt&quot;
&quot;os&quot;
&quot;time&quot;
&quot;github.com/aws/aws-lambda-go/lambda&quot;
&quot;github.com/aws/aws-sdk-go/aws&quot;
&quot;github.com/aws/aws-sdk-go/aws/session&quot;
&quot;github.com/aws/aws-sdk-go/service/apigateway&quot;
&quot;github.com/mitchellh/mapstructure&quot;
logging &quot;github.com/sirupsen/logrus&quot;
)
type UsageData struct {
APIKey string               `mapstructure:&quot;api_key&quot;`
Value  map[string][][]int64 `mapstructure:&quot;values&quot;`
}
func parseUsage(usage *apigateway.Usage) {
u := usage.Items
var data UsageData
err := mapstructure.Decode(u, &amp;data)
if err != nil {
panic(err)
}
fmt.Println(&quot;Decoded Data: &quot;, data)
fmt.Println(&quot;All the usage: &quot;, u)
fmt.Println(&quot;Items value one %v and value two %v: &quot;, u.Items.ValueOne, u.Items.ValueTwo)
}
func getUsagePlanInfo(client *apigateway.APIGateway) *apigateway.Usage {
currentDate := time.Now()
startDate := currentDate.Format(&quot;2006-01-02&quot;)
endDate := currentDate.Format(&quot;2006-01-02&quot;)
input := &amp;apigateway.GetUsageInput{
UsagePlanId: aws.String(os.Getenv(&quot;USAGE_PLAN_ID&quot;)),
KeyId:       aws.String(os.Getenv(&quot;API_KEY&quot;)),
StartDate:   aws.String(startDate),
EndDate:     aws.String(endDate),
}
results, _ := client.GetUsage(input)
logging.WithFields(logging.Fields{
&quot;UsagePlanId EV&quot;:  os.Getenv(&quot;USAGE_PLAN_ID&quot;),
&quot;KeyId EV&quot;:        os.Getenv(&quot;API_KEY&quot;),
&quot;StartDate EV&quot;:    startDate,
&quot;EndDate EV&quot;:      endDate,
&quot;Usage Plan Info&quot;: results,
}).Info(&quot;Values&quot;)
//fmt.Println(&quot;Usage Plan Data: &quot;, 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)
}

答案1

得分: 0

要获取这两个数字,你需要从映射中获取它们。如果你总是知道键,并且知道数组中只会有一个元素,你可以这样做:

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, %d\n", quota, remaining)
}

如果你有多个键或者不知道键的情况,你需要遍历映射并为每个键获取值。

英文:

To get the two numbers you would have to fetch them from the map. If you always know the key and you know that there will only be one element in the array you can do it like this

u := getUsagePlanInfo(srv)

items := u.Items

quota := *items[&quot;4wxq8mcov8&quot;][0][0]
remaining := *items[&quot;4wxq8mcov8&quot;][0][1]

to be safer you should do

if item, ok := items[&quot;4wxq8mcov8&quot;]; ok &amp;&amp; len(item) &gt; 0 &amp;&amp; len(item[0]) &gt; 1 {
  quota := *item[0][0]
  remaining := *item[0][1]

  fmt.Printf(&quot;%d, %d\n&quot;, quota, remaining)
}

If you have more than one key or you don't know the key you have to iterate the map and fetch values for each key

huangapple
  • 本文由 发表于 2021年9月1日 01:15:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/69002867.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定