質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Go

Go(golang)は、Googleで開発されたオープンソースのプログラミング言語です。

API

APIはApplication Programming Interfaceの略です。APIはプログラムにリクエストされるサービスがどのように動作するかを、デベロッパーが定めたものです。

Q&A

1回答

1454閲覧

GoでBinance APIを利用したcannnot unmarshalエラー

huskies

総合スコア2

Go

Go(golang)は、Googleで開発されたオープンソースのプログラミング言語です。

API

APIはApplication Programming Interfaceの略です。APIはプログラムにリクエストされるサービスがどのように動作するかを、デベロッパーが定めたものです。

0グッド

0クリップ

投稿2020/06/18 02:56

前提・実現したいこと

Golangを利用し、バイナンスのアカウントバランスへのアクセスを試みています。しかし、うまくアクセスできず、おそらくdoRequestの'resp'が上手く取れていないのですが解決方法が判明せず何かアイデアを頂ければ助かります!!

Binance api documentation: https://binance-docs.github.io/apidocs/spot/en/#change-log

go-binance json documentation: https://github.com/adshao/go-binance/blob/master/v2/account_service.go

発生している問題・エラーメッセージ

エラーメッセージ "url=/api/v3/account resp={"code":-2014,"msg":"API-key format invalid."}", "action=GetBalance err=json: cannot unmarshal object into Go value of type []Binance.Balance"

該当のソースコード

//apiKey = ' ' //apiSecret = ' ' package Binance import ( "bytes" "crypto/hmac" "crypto/sha256" "encoding/hex" "encoding/json" "io/ioutil" "log" "net/http" "net/url" "strconv" "time" ) const baseURL = "https://api.binance.com/" type APIClient struct { key string secret string httpClient *http.Client } func New(key, secret string) *APIClient { apiClient := &APIClient{key, secret, &http.Client{}} return apiClient } //header function that returns map[string]string which contains //access key, access timestamp, access sign, and content type func (api APIClient) header(method, endpoint string, body []byte) map[string]string { //define timestamp timestamp := strconv.FormatInt(time.Now().Unix(), 10) log.Println(timestamp) message := timestamp + method + endpoint + string(body) log.Println(message) // mac := hmac.New(sha256.New, []byte(api.secret)) mac.Write([]byte(message)) sign := hex.EncodeToString(mac.Sum(nil)) log.Println(api.key) log.Println(sign) return map[string]string{ "ACCESS-KEY": api.key, "ACCESS-TIMESTAMP": timestamp, "ACCESS-SIGN": sign, "Content-Type": "application/json", } } //request function using header function //return (body []byte, err error) func (api *APIClient) doRequest(method, urlPath string, query map[string]string, data []byte) (body []byte, err error) { //check url is correct baseURL, err := url.Parse(baseURL) if err != nil { return } apiURL, err := url.Parse(urlPath) if err != nil { return } endpoint := baseURL.ResolveReference(apiURL).String() log.Printf("action=doRequest endpoint=%s", endpoint) req, err := http.NewRequest(method, endpoint, bytes.NewBuffer(data)) if err != nil { return } q := req.URL.Query() for key, value := range query { q.Add(key, value) } req.URL.RawQuery = q.Encode() for key, value := range api.header(method, req.URL.RequestURI(), data) { req.Header.Add(key, value) } resp, err := api.httpClient.Do(req) if err != nil { return nil, err } defer resp.Body.Close() body, err = ioutil.ReadAll(resp.Body) if err != nil { return nil, err } return body, nil } // Account define account info type Account struct { MakerCommission int64 `json:"makerCommission"` TakerCommission int64 `json:"takerCommission"` BuyerCommission int64 `json:"buyerCommission"` SellerCommission int64 `json:"sellerCommission"` CanTrade bool `json:"canTrade"` CanWithdraw bool `json:"canWithdraw"` CanDeposit bool `json:"canDeposit"` Balances []Balance `json:"balances"` } // Balance define user balance of your account type Balance struct { Asset string `json:"asset"` Free string `json:"free"` Locked string `json:"locked"` } func (api *APIClient) GetBalance() ([]Balance, error){ url := "/api/v3/account" resp, err := api.doRequest("GET", url, map[string]string{}, nil) log.Println(resp) log.Printf("url=%s resp=%s", url, string(resp)) log.Println(resp) if err != nil { log.Printf("action=GetBalance err=%s", err.Error()) return nil, err } var balance []Balance err = json.Unmarshal(resp, &balance) log.Println(resp) if err != nil { log.Printf("action=GetBalance err=%s", err.Error()) return nil, err } return balance, nil }

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

jsonデコードエラーはデコード元を確認することは大切です。
ログにデコード元であるrespを表示しているのは素晴らしい。

json

1{"code":-2014,"msg":"API-key format invalid."}

このJSONを型[]Balanceにデコードしようとしていますが、この場合のJSONは以下のような形になっている必要があります。

json

1[{...},{...}]

GoのJSONデコーダのエラーメッセージはこういったことを伝えています。

respの内容が期待したものと異なる場合、それはAPIの利用方法に問題があったということが
respの内容からうかがえます。API-keyの書式に問題がありそうです。

投稿2020/06/19 00:46

nobonobo

総合スコア3367

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問