亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Go:如何在不解組的情況下傳遞 JSON 響應

Go:如何在不解組的情況下傳遞 JSON 響應

Go
慕斯709654 2022-12-13 10:41:03
使用 Go,我試圖從多個端點同時獲取一些 JSON 響應。我想將這些響應中的每一個附加到結構或映射中的字段,并將此結構/映射作為 JSON 對象返回。(前端模式的后端)。因此,我將使用某種標識符向 Go 應用程序發出 Web 請求。它會依次發出多個 Web 請求,并將數據編譯成一個大對象以作為響應返回。我使用 Fiber 作為我的框架,但任何通用的 Web 框架都是相似的:app.Get("/requests/:identifier", func(c *fiber.Ctx) error {    identifier := c.Params("identifier")    timeout := 1600 * time.Millisecond    client := httpclient.NewClient(httpclient.WithHTTPTimeout(timeout))    res, err := client.Get("https://www.example.com/endpoint?id=" + identifier, nil)    if err != nil{        logger.Error("Timout value exceeded")        return c.Status(503).SendString("Socket Timeout")    }    logger.Info("Fetch success: ")    // Heimdall returns the standard *http.Response object    body, err := ioutil.ReadAll(res.Body)    code := 200    response := &main_response{        Service1: body,    }    return c.Status(code).JSON(response)})我遇到的問題是,我不需要在 Go 中解組這些數據,因為我不需要它(我只是簡單地傳遞它)。我是否必須解組它才能像這樣將它設置為我的響應結構中的一個字段?type main_response struct {    Service1 []byte `json:"service1"`    Service2 map[string]string `json:"service2"`    Service3 map[string]interface{} `json:"service3"`}(我嘗試了幾種不同的方法來實現這一點。嘗試使用字節數組似乎對響應進行了 base64 編碼)我想在返回之前將該結構編組為 JSON,所以也許我別無選擇,因為我想不出一種方法來告訴 Go“只編組主結構,其他一切都已經是 JSON”。在這一點上,我幾乎感覺最好還是構建一個字符串。
查看完整描述

1 回答

?
aluckdog

TA貢獻1847條經驗 獲得超7個贊

使用json.RawMessage[]byte包含的 JSON 直接復制到響應 JSON 文檔:

type main_response struct {

    Service1 json.RawMessage `json:"service1"`

    ...

}


response := &main_response{

    Service1: body,

}


return c.Status(code).JSON(response)


查看完整回答
反對 回復 2022-12-13
  • 1 回答
  • 0 關注
  • 91 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號