恐慌:接口转换:接口 {} 是字符串,不是 float64

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

我正在尝试将这个简单的 python 函数转换为 golang,但遇到了这个错误的问题

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

这是 golang 版本(代码更长,代码比应该的更复杂)

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
}

所以我在这里弄错了什么?以前我有错误 cannot use price (type interface {}) as type float64 in return argument: need type assertion 现在我尝试使用 pricer := price.(float64) 的类型断言现在这个错误

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

它在错误中告诉你,price是一个字符串,而不是float64,所以你需要做(大概):

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

更好的方法可能是改为

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

错误已经告诉你:价格是一个字符串。所以它可能来自 JSON,看起来像:

{
   "price": "123"
}

但不是

{
   "price": 123
}

第一个解组为字符串。第二次解组为 float64.

在你的情况下,你必须解析它:

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