I'm trying to parse this petition (https://www.binance.com/api/v1/depth?symbol=MDABTC&limit=500)
I was having tons of problems to create an struct for it, so I used an automated tool, this is what my struct looks like:
type orderBook struct {
Bids [][]interface{} `json:"Bids"`
Asks [][]interface{} `json:"Asks"`
}
I recover and parse the petition by doing:
url := "https://www.binance.com/api/v1/depth?symbol=MDABTC&limit=500"
resp, err := http.Get(url)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}else{
book := orderBook{}
if err := json.Unmarshal(body, &book); err != nil {
panic(err)
}
But whenever I try to make an operation with the struct, like:
v := book.Asks[i][0] * book.Asks[i][1]
I get an error:
invalid operation: book.Asks[i][0] * book.Asks[i][1] (operator * not defined on interface)
How do I define it? Do I need to create an struct for bids/asks
, if so, how would that look like?
Sorry if this seems basic, I just started learning go.
In Golang Spec
Fetching an underlying value of string type you need to type assert to string from interface.
For performing an arithmetic operation on same you needs to convert string into float64 to take into account decimal values
Checkout code on Go playground
Note that you could define proper structs that unmarshal from the JSON document by implementing the
json.Unmarshaler
interface.For example (on the Go Playground):
As such, unmarshaling those documents looks idiomatic: