猿问

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

使用 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”。在这一点上,我几乎感觉最好还是构建一个字符串。


慕斯709654
浏览 104回答 1
1回答

aluckdog

使用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)
随时随地看视频慕课网APP

相关分类

Go
我要回答