使用 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)
- 1 回答
- 0 關注
- 91 瀏覽
添加回答
舉報
0/150
提交
取消