gopython-requeststype-assertion

panic: interface conversion: interface {} is string, not float64


I am trying to convert this simple python function to golang, but facing issues with this error

panic: interface conversion: interface {} is string, not float64

python

def binance(crypto: str, currency: str):
    import requests

    base_url = "https://www.binance.com/api/v3/avgPrice?symbol={}{}"
    base_url = base_url.format(crypto, currency)
  
    try:
        result = requests.get(base_url).json()
        print(result)
        result = result.get("price")
    except Exception as e:
        
        return False
    return result

here is the golang version(longer code and more complicated code than should be)

func Binance(crypto string, currency string) (float64, error) {
    req, err := http.NewRequest("GET", fmt.Sprintf("https://www.binance.com/api/v3/avgPrice?symbol=%s%s", crypto, currency), nil)
    if err != nil {
         fmt.Println("Error is req: ", err)
    }
    
    client := &http.Client{}
    
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println("error in send req: ", err)
    }
    respBody, _ := ioutil.ReadAll(resp.Body)
    var respMap map[string]interface{}
    log.Printf("body=%v",respBody)
    json.Unmarshal(respBody,&respMap) 
    log.Printf("response=%v",respMap)
    price := respMap["price"]
    log.Printf("price=%v",price)

    pricer := price.(float64)
    return pricer, err
}

so what am I getting wrong here? Previously i had the error cannot use price (type interface {}) as type float64 in return argument: need type assertion and now i tried the type assertion with pricer := price.(float64) and now this error

panic: interface conversion: interface {} is string, not float64

Solution

  • It's telling you in the error, price is a string, not a float64, so you need to do (presumably):

    pricer := price.(string)
    return strconv.ParseFloat(pricer, 64)
    

    A better way would probably be to instead do

    type response struct {
        Price float64 `json:",string"`
    }
    r := &response{}
    respBody, _ := ioutil.ReadAll(resp.Body)
    err := json.Unmarshal(respBody, r) 
    return r.Price, err
    

    The "string" option signals that a field is stored as JSON inside a JSON-encoded string. It applies only to fields of string, floating point, integer, or boolean types.

    https://pkg.go.dev/encoding/json#Marshal