-
Notifications
You must be signed in to change notification settings - Fork 0
/
amazonrank.go
86 lines (75 loc) · 2.17 KB
/
amazonrank.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package main
import (
"fmt"
"github.com/mackerelio/mackerel-client-go"
"github.com/ngs/go-amazon-product-advertising-api/amazon"
"gopkg.in/yaml.v2"
"io/ioutil"
"log"
"strings"
"time"
)
type Config struct {
Region amazon.Region `yaml:"amazon_region"`
AccessKey string `yaml:"amazon_access_key"`
AccessSecret string `yaml:"amazon_access_secret"`
Account string `yaml:"amazon_account"`
MackerelKey string `yaml:"mackerel_key"`
ASINs []string `yaml:"asins"`
Prefix string `yaml:"metric_prefix"`
}
func retry(attempts int, sleep time.Duration, callback func() error) (err error) {
for i := 0; ; i++ {
err = callback()
if err == nil {
return
}
if i >= (attempts - 1) {
break
}
time.Sleep(sleep)
// log.Println("Retrying", i+1, "times after error:", err)
}
return fmt.Errorf("After %d attempts, last error: %s", attempts, err)
}
func main() {
buf, err := ioutil.ReadFile("./config.yaml")
if err != nil {
log.Fatalf("Unable to open the config yaml %v", err)
}
var config Config
err = yaml.Unmarshal(buf, &config)
if err != nil {
log.Fatalf("Unable to parse the config yaml %v", err)
}
aclient, err := amazon.New(config.AccessKey, config.AccessSecret, config.Account, config.Region)
if err != nil {
log.Fatalf("Unable to setup an Amazon client %v", err)
}
time.Sleep(5 * time.Second)
var ilres *amazon.ItemLookupResponse
err = retry(10, 3*time.Second, func() (err error) {
ilres, err = aclient.ItemLookup(amazon.ItemLookupParameters{
ResponseGroups: []amazon.ItemLookupResponseGroup{amazon.ItemLookupResponseGroupSalesRank},
ItemIDs: config.ASINs,
}).Do()
return
})
if err != nil {
if !strings.Contains(err.Error(), "NoExactMatches") {
log.Fatalf("Unable to search an Item %v", err)
}
} else {
mclient := mackerel.NewClient(config.MackerelKey)
for _, item := range ilres.Items.Item {
log.Printf("%s %v\n", item.ASIN, item.SalesRank)
mclient.PostServiceMetricValues("Books", []*mackerel.MetricValue{
&mackerel.MetricValue{
Name: config.Prefix + "." + item.ASIN,
Time: time.Now().Unix(),
Value: item.SalesRank,
},
})
}
}
}