【问题标题】:error "data1.Body undefined (type []byte has no field or method Body)" when trying to decode a json's body尝试解码 json 的主体时出现错误“data1.Body undefined (type []byte has no field or method Body)”
【发布时间】:2022-01-10 03:04:54
【问题描述】:

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

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
}

【问题讨论】:

  • 使用 std 库 http 包,您会发现更少的惊喜和更多的示例材料,特别是因为您仍然不熟悉该语言。没有理由使用fasthttp 包,除非您遇到了专门设计用来解决的问题。
  • 好的,所以我试图在 json 中获取大约 45 页的 1000 个项目,如果我想要速度,我应该使用什么?
  • net/http 面临的瓶颈是什么? “45 页”毫无意义,一次 45 个请求几乎没有什么可担心的。如果您在分配和垃圾收集方面遇到瓶颈(在 json 解码之外,因为这是一个完全不同的包),也许可以查看fasthttp,但由于您甚至还没有功能代码,我敢打赌您还没有以此为基准。
  • 谢谢你,但有什么方法可以让我的代码异步快速http获取请求?
  • @Ultimate,即使是 fasthttp 文档本身也说你应该坚持使用 net/http。您可能会发现这个问题对于弄清楚如何对您的 http 请求进行排队或扇出很有用:stackoverflow.com/questions/70217232/…

标签: arrays json go fasthttp


【解决方案1】:
    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 但由于fasthttp 已经将数据读入[]byte,使用json.Unmarshal 会更合适:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 2020-05-29
    • 2013-10-20
    • 1970-01-01
    • 2019-10-18
    • 2020-12-14
    • 2013-09-11
    相关资源
    最近更新 更多