Last active
November 26, 2017 05:17
-
-
Save py0n/82fa433095d77cd57b673545d8900246 to your computer and use it in GitHub Desktop.
Product Advertising API から書籍情報を取得する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package paapi | |
import ( | |
"crypto/hmac" | |
"crypto/sha256" | |
"encoding/base64" | |
"io/ioutil" | |
"log" | |
"net/http" | |
"net/url" | |
"strings" | |
"time" | |
xj "github.com/basgys/goxml2json" | |
errors "github.com/pkg/errors" | |
) | |
var endpoint = "http://ecs.amazonaws.jp/onca/xml" | |
func GetJsonFromPaapi(accessKeyId, secretKeyId, associateTag, asin string) (string, error) { | |
u, err := url.Parse(endpoint) | |
if err != nil { | |
return "", err | |
} | |
delimiter := "?" | |
if len(u.Query()) > 0 { | |
delimiter = "&" | |
} | |
v := url.Values{} | |
v.Add("AWSAccessKeyId", accessKeyId) | |
v.Add("AssociateTag", associateTag) | |
v.Add("ItemId", asin) | |
v.Add("Operation", "ItemLookup") | |
v.Add("ResponseGroup", "ItemAttributes,Images") | |
v.Add("Service", "AWSCommerceService") | |
v.Add("Timestamp", time.Now().Format("2006-01-02T15:04:05Z")) | |
signature := makeHMAC(strings.Join([]string{ | |
"GET", | |
u.Hostname(), | |
u.EscapedPath(), | |
v.Encode(), | |
}, "\n"), secretKeyId) | |
v.Add("Signature", signature) | |
u, err = url.Parse(u.String() + delimiter + v.Encode()) | |
if err != nil { | |
return "", errors.Wrap(err, "failure to create URL for PAAPI") | |
} | |
response, err := http.Get(u.String()) | |
if err != nil { | |
return "", errors.Wrap(err, "failure to get XML from PAAPI") | |
} | |
defer response.Body.Close() | |
byteArray, err := ioutil.ReadAll(response.Body) | |
if err != nil { | |
return "", errors.Wrap(err, "failure to get XML from PAAPI") | |
} | |
xml := strings.NewReader(string(byteArray)) | |
json, err := xj.Convert(xml) | |
if err != nil { | |
return "", errors.Wrap(err, "failure to convert XML to JSON") | |
log.Fatal(err) | |
} | |
return json.String(), nil | |
} | |
// http://cipepser.hatenablog.com/entry/2017/05/27/100516 | |
func makeHMAC(msg, key string) string { | |
mac := hmac.New(sha256.New, []byte(key)) | |
mac.Write([]byte(msg)) | |
return base64.StdEncoding.EncodeToString(mac.Sum(nil)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment