-1

所以我再次尝试获取这些数据,但它返回一个错误

data.Body undefined (type []byte has no field or method Body)

在此代码的第 16 和 23 行。所以当它解码 json 如果有人可以帮助我,这是我的代码

func SkyblockActiveAuctions() (structs.SkyblockActiveAuctions, error) {
    var auctions structs.SkyblockActiveAuctions
    startTime := time.Now()
    statusCode, data, err := fasthttp.Get(nil, "https://api.hypixel.net/skyblock/auctions")
    if err != nil {
        return auctions, err
    }
    fmt.Println(statusCode)
    var totalPages = auctions.TotalAuctions
    for i := 0; i < totalPages; i++ {
        statusCode, data1, err := fasthttp.Get(nil, "https://api.hypixel.net/skyblock/auctions")
        if err != nil {
            return auctions, err
        }
        fmt.Println(statusCode)
        json.NewDecoder(data1.Body).Decode(&auctions)
        fmt.Println(auctions.LastUpdated)
    }
    endTime := time.Now()
    var timeTook = endTime.Sub(startTime).Milliseconds()
    fmt.Println(data)

    json.NewDecoder(data.Body).Decode(&auctions)

    fmt.Println(auctions.LastUpdated)
    fmt.Println(timeTook)

    return auctions, err
}
4

1 回答 1

2
    json.NewDecoder(data.Body).Decode(&auctions)
data.Body undefined (type []byte has no field or method Body)

data已经是响应的正文了

json.NewDecoder期望 anio.Reader但由于fasthttp已经将数据读入[]byte,因此更适合使用json.Unmarshal

    err := json.Unmarshal(data, &auctions)
    if err != nil {
         return nil, err
    }

不要忘记处理来自json.Unmarshal(或,json.Decoder.Decode就此而言)的错误。 acutions如果 Json 无法解析,将不会保存预期的数据,因此您应该处理这种可能性。

于 2021-12-03T19:17:17.257 回答