Go:如何在不解组的情况下传递 JSON 响应

Go: How do I pass a JSON response without unmarshalling it

使用 Go,我试图从多个端点同时获取一些 JSON 响应。我想将这些响应中的每一个附加到结构或映射中的字段,并将 return 这个 struct/map 作为一个 JSON 对象。 (前端模式的后端)。因此,我将使用某种标识符向 Go 应用程序发出 Web 请求。它会依次发出几个网络请求,并将数据编译成一个大对象以return作为响应。

我使用 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 编码)

我想在 return 之前将该结构编组为 JSON,所以也许我别无选择,因为我想不出一种方法来告诉 Go“只编组主要的struct,其他一切都已经 JSON”。几乎感觉我现在最好还是构建一个字符串。

使用json.RawMessage将包含JSON的[]byte直接复制到响应JSON文档:

type main_response struct {
    Service1 json.RawMessage `json:"service1"`
    ...
}

response := &main_response{
    Service1: body,
}

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