Home > Blockchain >  error "data1.Body undefined (type []byte has no field or method Body)" when trying to deco
error "data1.Body undefined (type []byte has no field or method Body)" when trying to deco

Time:12-04

So again im trying to get this data but it is returning an error of

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

on line 16 and 23 of this code. so when its decoding the json If anyone could help me, here is my code

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
}

CodePudding user response:

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

data is already the body of the response.

json.NewDecoder expects an io.Reader but since fasthttp has already read the data into []byte, it would be more appropriate to use json.Unmarshal:

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

Don't forget to handle errors from json.Unmarshal (or, from json.Decoder.Decode for that matter). acutions won't hold the expected data if the Json failed to parse, so you should handle that possiblity.

  • Related