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

ube*_*ebu -1 go python-requests type-assertion

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

panic: interface conversion: interface {} is string, not float64
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

这是 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
}
Run Code Online (Sandbox Code Playgroud)

那么我在这里犯了什么错呢?以前我遇到了错误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
Run Code Online (Sandbox Code Playgroud)

dav*_*ave 5

它在错误中告诉您,price是一个字符串,而不是 float64,因此您需要执行以下操作(大概):

pricer := price.(string)
return strconv.ParseFloat(pricer, 64)
Run Code Online (Sandbox Code Playgroud)

更好的方法可能是

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

“string”选项表示字段以 JSON 形式存储在 JSON 编码的字符串中。它仅适用于字符串、浮点、整数或布尔类型的字段。

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